Essai au propre

This commit is contained in:
Gauvain Boiché
2020-04-01 16:45:39 +02:00
parent f282fd0d32
commit 745270ab61
1538 changed files with 80 additions and 351590 deletions

View File

@@ -1,7 +0,0 @@
vendor
composer.lock
composer.phar
phpunit.xml
phpmd.xml
phpdox.xml
clover.xml

View File

@@ -1,45 +0,0 @@
before_commands:
- "composer install --no-dev --prefer-source"
tools:
external_code_coverage:
timeout: 600
php_code_coverage:
enabled: true
php_code_sniffer:
enabled: true
config:
standard: PSR2
filter:
paths: ["src/*", "tests/*"]
php_cpd:
enabled: true
excluded_dirs: ["docs", "examples", "tests", "vendor"]
php_cs_fixer:
enabled: true
config:
level: all
filter:
paths: ["src/*", "tests/*"]
php_loc:
enabled: true
excluded_dirs: ["docs", "examples", "tests", "vendor"]
php_mess_detector:
enabled: true
config:
ruleset: phpmd.xml.dist
design_rules: { eval_expression: false }
filter:
paths: ["src/*"]
php_pdepend:
enabled: true
excluded_dirs: ["docs", "examples", "tests", "vendor"]
php_analyzer:
enabled: true
filter:
paths: ["src/*", "tests/*"]
php_hhvm:
enabled: true
filter:
paths: ["src/*", "tests/*"]
sensiolabs_security_checker: true

View File

@@ -1,11 +0,0 @@
set -x
if [ "$TRAVIS_PHP_VERSION" = 'hhvm' ] || [ "$TRAVIS_PHP_VERSION" = 'hhvm-nightly' ] ; then
curl -sS https://getcomposer.org/installer > composer-installer.php
hhvm composer-installer.php
hhvm -v ResourceLimit.SocketDefaultTimeout=30 -v Http.SlowQueryThreshold=30000 composer.phar update --prefer-source
hhvm -v ResourceLimit.SocketDefaultTimeout=30 -v Http.SlowQueryThreshold=30000 composer.phar install --dev --prefer-source
else
composer self-update
composer update --prefer-source
composer install --dev --prefer-source
fi

View File

@@ -1,28 +0,0 @@
language: php
php:
- 5.3.3
- 5.3
- 5.4
- 5.5
- 5.6
- hhvm
- hhvm-nightly
before_script:
- sh .travis.install.sh
script:
- ./vendor/bin/phpunit --disallow-test-output --report-useless-tests --coverage-clover ./clover.xml --group=Coverage
- ./vendor/bin/phpunit --disallow-test-output --report-useless-tests --strict --exclude-group=Performance,Coverage
- php -n ./vendor/bin/phpunit --group=Performance
- ./vendor/bin/phpcs --standard=PSR2 ./src/ ./tests/
matrix:
allow_failures:
- php: hhvm
- php: hhvm-nightly
after_script:
- wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover ./clover.xml

View File

@@ -1,35 +0,0 @@
# Contributing
* Coding standard for the project is [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)
* The project will follow strict [object calisthenics](http://www.slideshare.net/guilhermeblanco/object-calisthenics-applied-to-php)
* Any contribution must provide tests for additional introduced conditions
* Any un-confirmed issue needs a failing test case before being accepted
* Pull requests must be sent from a new hotfix/feature branch, not from `master`.
## Installation
To install the project and run the tests, you need to clone it first:
```sh
$ git clone git://github.com/Ocramius/ProxyManager.git
```
You will then need to run a composer installation:
```sh
$ cd ProxyManager
$ curl -s https://getcomposer.org/installer | php
$ php composer.phar update
```
## Testing
The PHPUnit version to be used is the one installed as a dev- dependency via composer:
```sh
$ ./vendor/bin/phpunit
```
Accepted coverage for new contributions is 80%. Any contribution not satisfying this requirement
won't be merged.

View File

@@ -1,38 +0,0 @@
<?php
/**
* This example demonstrates how an access interceptor scope localizer
* (which is a specific type of smart reference) is safe to use to
* proxy fluent interfaces.
*/
require_once __DIR__ . '/../vendor/autoload.php';
use ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory;
class FluentCounter
{
public $counter = 0;
/** @return FluentCounter */
public function fluentMethod()
{
$this->counter += 1;
return $this;
}
}
$factory = new AccessInterceptorScopeLocalizerFactory();
$foo = new FluentCounter();
/* @var $proxy FluentCounter */
$proxy = $factory->createProxy(
$foo,
array('fluentMethod' => function ($proxy) { echo "pre-fluentMethod #{$proxy->counter}!\n"; }),
array('fluentMethod' => function ($proxy) { echo "post-fluentMethod #{$proxy->counter}!\n"; })
);
$proxy->fluentMethod()->fluentMethod()->fluentMethod()->fluentMethod();
echo 'The proxy counter is now at ' . $proxy->counter . "\n";
echo 'The real instance counter is now at ' . $foo->counter . "\n";

View File

@@ -1,46 +0,0 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use ProxyManager\Factory\LazyLoadingGhostFactory;
class Foo
{
private $foo;
public function __construct()
{
sleep(5);
}
public function setFoo($foo)
{
$this->foo = (string) $foo;
}
public function getFoo()
{
return $this->foo;
}
}
$startTime = microtime(true);
$factory = new LazyLoadingGhostFactory();
for ($i = 0; $i < 1000; $i += 1) {
$proxy = $factory->createProxy(
'Foo',
function ($proxy, $method, $parameters, & $initializer) {
$initializer = null;
$proxy->setFoo('Hello World!');
return true;
}
);
}
var_dump('time after 1000 instantiations: ' . (microtime(true) - $startTime));
echo $proxy->getFoo() . "\n";
var_dump('time after single call to doFoo: ' . (microtime(true) - $startTime));

View File

@@ -1,36 +0,0 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use ProxyManager\Factory\RemoteObject\Adapter\XmlRpc;
use ProxyManager\Factory\RemoteObjectFactory;
use Zend\XmlRpc\Client;
if (! class_exists('Zend\XmlRpc\Client')) {
echo "This example needs Zend\\XmlRpc\\Client to run. \n In order to install it, "
. "please run following:\n\n"
. "\$ php composer.phar require zendframework/zend-xmlrpc:2.*\n\n";
exit(2);
}
class Foo
{
public function bar()
{
return 'bar local!';
}
}
$factory = new RemoteObjectFactory(
new XmlRpc(new Client('http://localhost:9876/remote-proxy/remote-proxy-server.php'))
);
$proxy = $factory->createProxy('Foo');
try {
var_dump($proxy->bar()); // bar remote !
} catch (\Zend\Http\Client\Adapter\Exception\RuntimeException $error) {
echo "To run this example, please following before:\n\n\$ php -S localhost:9876 -t \"" . __DIR__ . "\"\n";
exit(2);
}

View File

@@ -1,20 +0,0 @@
<?php
use Zend\XmlRpc\Server;
require_once __DIR__ . '/../../vendor/autoload.php';
class Foo
{
public function bar()
{
return 'bar remote!';
}
}
$server = new Server();
$server->setClass(new Foo(), 'Foo');
$server->setReturnResponse(false);
$server->handle();

View File

@@ -1,23 +0,0 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use ProxyManager\Factory\AccessInterceptorValueHolderFactory;
class Foo
{
public function doFoo()
{
echo "Foo!\n";
}
}
$factory = new AccessInterceptorValueHolderFactory();
$proxy = $factory->createProxy(
new Foo(),
array('doFoo' => function () { echo "pre-foo!\n"; }),
array('doFoo' => function () { echo "post-foo!\n"; })
);
$proxy->doFoo();

View File

@@ -1,39 +0,0 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
class Foo
{
public function __construct()
{
sleep(5);
}
public function doFoo()
{
echo "Foo!";
}
}
$startTime = microtime(true);
$factory = new LazyLoadingValueHolderFactory();
for ($i = 0; $i < 1000; $i += 1) {
$proxy = $factory->createProxy(
'Foo',
function (& $wrappedObject, $proxy, $method, $parameters, & $initializer) {
$initializer = null;
$wrappedObject = new Foo();
return true;
}
);
}
var_dump('time after 1000 instantiations: ' . (microtime(true) - $startTime));
$proxy->doFoo();
var_dump('time after single call to doFoo: ' . (microtime(true) - $startTime));

View File

@@ -1,197 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager - Tuning the ProxyManager for production</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php, production" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">Access Interceptor Scope Localizer Proxy</h3>
<p>An access interceptor scope localizer is a smart reference proxy that allows you to dynamically define logic to be executed before or after any of the proxied object's methods' logic.</p>
<p>It works exactly like the <a href="access-interceptor-value-holder-proxy.html">access interceptor value holder</a>, with some minor differences in behavior.</p>
<p>The working concept of an access interceptor scope localizer is to localize scope of a proxied object:</p>
<pre>
<code class="php">
class Example
{
protected $foo;
protected $bar;
protected $baz;
public function doFoo()
{
// ...
}
}
class ExampleProxy extends Example
{
public function __construct(Example $example)
{
$this->foo = &amp; $example->foo;
$this->bar = &amp; $example->bar;
$this->baz = &amp; $example->baz;
}
public function doFoo()
{
return parent::doFoo();
}
}
</code>
</pre>
<p>This allows to create a mirror copy of the real instance, where any change in the proxy or in the real instance is reflected in both objects.</p>
<p>The main advantage of this approach is that the proxy is now safe against fluent interfaces, which would break an <a href="access-interceptor-value-holder-proxy.html">access interceptor value holder</a> instead.</p>
<hr />
<h3>Differences with <a href="access-interceptor-value-holder-proxy.html">access interceptor value holder</a>:</h3>
<ul>
<li>It does <strong>NOT</strong> implement the <code>ProxyManager\Proxy\ValueHolderInterface</code>, since the proxy itself does not keep a reference to the original object being proxied</li>
<li>In all interceptor methods (see <a href="access-interceptor-value-holder-proxy.html">access interceptor value holder</a>), the $instance passed in is the proxy itself. There is no way to gather a reference to the original object right now, and that's mainly to protect from misuse.</li>
</ul>
<hr />
<h3>Known limitations</h3>
<ul>
<li>It is <strong>NOT</strong> possible to intercept access to public properties</li>
<li>It is <strong>NOT</strong> possible to proxy interfaces, since this proxy relies on <code>parent::method()</code> calls. Interfaces obviously don't provide a parent method implementation.</li>
<li>calling unset on a property of an access interceptor scope localizer (or the real instance) will cause the two objects to be un-synchronized, with possible unexpected behaviour.</li>
<li>serializing or un-serializing an access interceptor scope localizer (or the real instance) will not cause the real instance (or the proxy) to be serialized or un-serialized</li>
<li>if a proxied object contains private properties, then an exception will be thrown if you use PHP <code>&lt; 5.4.0</code>.</li>
</ul>
<hr />
<h3>Example</h3>
<p>Here's an example of how you can create and use an access interceptor scope localizer :</p>
<pre>
<code class="php">
&lt;?php
use ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory as Factory;
require_once __DIR__ . '/vendor/autoload.php';
class Foo
{
public function doFoo()
{
echo "Foo!\n";
}
}
$factory = new Factory();
$proxy = $factory->createProxy(
new Foo(),
array('doFoo' => function () { echo "PreFoo!\n"; }),
array('doFoo' => function () { echo "PostFoo!\n"; })
);
$proxy->doFoo();
</code>
</pre>
<p>This send something like following to your output:</p>
<pre>
<code class="php">
PreFoo!
Foo!
PostFoo!
</code>
</pre>
<p>This is pretty much the same logic that you can find in <a href="access-interceptor-value-holder-proxy.html">access interceptor value holder</a>.</p>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

View File

@@ -1,208 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager - Tuning the ProxyManager for production</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php, production" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">Access Interceptor Value Holder Proxy</h3>
<p>An access interceptor value holder is a smart reference proxy that allows you to dynamically define logic to be executed before or after any of the wrapped object's methods logic.</p>
<p>It wraps around a real instance of the object to be proxied, and can be useful for things like:</p>
<ul>
<li>caching execution of slow and heavy methods</li>
<li>log method calls</li>
<li>debugging</li>
<li>event triggering</li>
<li>handling of orthogonal logic, and <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" target="_blank">AOP</a> in general</li>
</ul>
<hr />
<h3>Example</h3>
<p>Here's an example of how you can create and use an access interceptor value holder:</p>
<pre>
<code class="php">
&lt;?php
use ProxyManager\Factory\AccessInterceptorValueHolderFactory as Factory;
require_once __DIR__ . '/vendor/autoload.php';
class Foo
{
public function doFoo()
{
echo "Foo!\n";
}
}
$factory = new Factory();
$proxy = $factory->createProxy(
new Foo(),
array('doFoo' => function () { echo "PreFoo!\n"; }),
array('doFoo' => function () { echo "PostFoo!\n"; })
);
$proxy->doFoo();
</code>
</pre>
<p>This send something like following to your output:</p>
<pre>
<code class="php">
PreFoo!
Foo!
PostFoo!
</code>
</pre>
<hr />
<h3>Implementing pre- and post- access interceptors</h3>
<p>A proxy produced by the <code><a href="https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Factory/AccessInterceptorValueHolderFactory.php" target="_blank">ProxyManager\Factory\AccessInterceptorValueHolderFactory</a></code> implements both the <code><a href="https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/ValueHolderInterface.php" target="_blank">ProxyManager\Proxy\ValueHolderInterface</a></code> and the <code><a href="https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/ValueHolderInterface.php" target="_blank">ProxyManager\Proxy\AccessInterceptorInterface</a></code>.</p>
<p>Therefore, you can set an access interceptor callback by calling:</p>
<pre>
<code class="php">
$proxy->setMethodPrefixInterceptor('methodName', function () { echo 'pre'; });
$proxy->setMethodSuffixInterceptor('methodName', function () { echo 'post'; });
</code>
</pre>
<p>You can also listen to public properties access by attaching interceptors to <code>__get</code>, <code>__set</code>, <code>__isset</code> and <code>__unset</code>.</p>
<p>A prefix interceptor (executed before method logic) should have following signature:</p>
<pre>
<code class="php">
/**
* @var object $proxy the proxy that intercepted the method call
* @var object $instance the wrapped instance within the proxy
* @var string $method name of the called method
* @var array $params sorted array of parameters passed to the intercepted
* method, indexed by parameter name
* @var bool $returnEarly flag to tell the interceptor proxy to return early, returning
* the interceptor's return value instead of executing the method logic
*
* @return mixed
*/
$prefixInterceptor = function ($proxy, $instance, $method, $params, &amp; $returnEarly) {};
</code>
</pre>
A suffix interceptor (executed after method logic) should have following signature:
<pre>
<code class="php">
/**
* @var object $proxy the proxy that intercepted the method call
* @var object $instance the wrapped instance within the proxy
* @var string $method name of the called method
* @var array $params sorted array of parameters passed to the intercepted
* method, indexed by parameter name
* @var mixed $returnValue the return value of the intercepted method
* @var bool $returnEarly flag to tell the proxy to return early, returning the interceptor's
* return value instead of the value produced by the method
*
* @return mixed
*/
$suffixInterceptor = function ($proxy, $instance, $method, $params, $returnValue, & $returnEarly) {};
</code>
</pre>
<hr />
<h3>Tuning performance for production</h3>
<p>See <a href="production.html">Tuning ProxyManager for Production</a>.</p>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

View File

@@ -1,139 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager - Contributing</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php, contributing" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">Contributing</h3>
<ul>
<li>Coding standard for the project is <a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md" target-"_blank">PSR-2</a></li>
<li>The project will follow strict <a href="http://www.slideshare.net/guilhermeblanco/object-calisthenics-applied-to-php" target-"_blank">object calisthenics</a></li>
<li>Any contribution must provide tests for additional introduced conditions</li>
<li>Any un-confirmed issue needs a failing test case before being accepted</li>
<li>Pull requests must be sent from a new hotfix/feature branch, not from master.</li>
</ul>
<hr />
<h3 class="section-title">Installation</h3>
<p>To install the project and run the tests, you need to clone it first:</p>
<pre>
<code class="sh">
$ git clone git://github.com/Ocramius/ProxyManager.git
</code>
</pre>
<p>You will then need to run a composer installation:</p>
<pre>
<code class="sh">
$ cd ProxyManager
$ curl -s https://getcomposer.org/installer | php
$ php composer.phar update
</code>
</pre>
<hr />
<h3 class="section-title">Testing</h3>
<p>The PHPUnit version to be used is the one installed as a dev- dependency via composer:</p>
<pre>
<code class="sh">
$ ./vendor/bin/phpunit
</code>
</pre>
<p>Accepted coverage for new contributions is 80%. Any contribution not satisfying this requirement won't be merged.</p>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

View File

@@ -1,100 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">License</h3>
<p>Copyright (c) 2013 Marco Pivetta</p>
<p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</p>
<p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</p>
<p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</p>
<hr />
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

View File

@@ -1,113 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager - Credits</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php, credits" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">Credits</h3>
<p>The idea was originated by a <a href="http://marco-pivetta.com/proxy-pattern-in-php/" target="_blank">talk about Proxies in PHP OOP</a> that I gave at the <a href="https://twitter.com/phpugffm" target="_blank">@phpugffm</a> in January 2013.</p>
<hr />
<h3>Contributors</h3>
<ul>
<li><a href="https://github.com/Ocramius" target="_blank">Marco Pivetta</a></li>
<li><a href="https://github.com/malukenho" target="_blank">Jefersson Nathan</a></li>
<li><a href="https://github.com/blanchonvincent" target="_blank">Blanchon Vincent</a></li>
<li><a href="https://github.com/staabm" target="_blank">Markus Staab</a></li>
<li><a href="https://github.com/gws" target="_blank">Gordon Stratton</a></li>
<li><a href="https://github.com/prolic" target="_blank">Prolic</a></li>
<li><a href="https://github.com/guilro" target="_blank">Guillaume Royer</a></li>
<li><a href="https://github.com/reiz" target="_blank">Robert Reiz</a></li>
<li><a href="https://github.com/leedavis81" target="_blank">Lee Davis</a></li>
<li><a href="https://github.com/flip111" target="_blank">flip111</a></li>
<li><a href="https://github.com/krymen" target="_blank">Krzysztof Menzyk</a></li>
<li><a href="https://github.com/Xerkus" target="_blank">Aleksey Khudyakov</a></li>
<li><a href="https://github.com/asm89" target="_blank">Alexander</a></li>
<li><a href="https://github.com/raulfraile" target="_blank">Raul Fraile</a></li>
</ul>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

View File

@@ -1,203 +0,0 @@
html { font-family: sans-serif; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; }
body { margin: 0; }
article, aside, details, figcaption, figure, footer, header, hgroup, main, nav, section, summary { display: block; }
audio, canvas, progress, video { display: inline-block; vertical-align: baseline; }
audio:not([controls]) { display: none; height: 0; }
[hidden], template { display: none; }
a { background: transparent; }
a:active, a:hover { outline: 0; }
abbr[title] { border-bottom: 1px dotted; }
b, strong { font-weight: bold; }
dfn { font-style: italic; }
h1 { font-size: 2em; margin: 0.67em 0; }
mark { background: #ff0; color: #000; }
small { font-size: 80%; }
sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; }
sup { top: -0.5em; }
sub { bottom: -0.25em; }
img { border: 0; }
svg:not(:root) { overflow: hidden; }
figure { margin: 1em 40px; }
hr { -moz-box-sizing: content-box; box-sizing: content-box; height: 0; }
pre { overflow: auto; }
code, kbd, pre, samp { font-family: monospace, monospace; font-size: 1em; }
button, input, optgroup, select, textarea { color: inherit; font: inherit; margin: 0; }
button { overflow: visible; }
button, select { text-transform: none; }
button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; }
button[disabled], html input[disabled] { cursor: default; }
button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; }
input { line-height: normal; }
input[type="checkbox"], input[type="radio"] { box-sizing: border-box; padding: 0; }
input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button { height: auto; }
input[type="search"] { -webkit-appearance: textfield; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box; }
input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; }
fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; }
legend { border: 0; padding: 0; }
textarea { overflow: auto; }
optgroup { font-weight: bold; }
table { border-collapse: collapse; border-spacing: 0; }
td, th { padding: 0; }
h1, h2, h3, h4, h5, h6, p, ul, ol, li { margin: 0; padding: 0; line-height: normal; }
a { color: #31811D; text-decoration: none; }
a:hover { color: #2F611C; text-decoration: none; }
strong { font-weight: 600; }
h3 { margin-bottom: 1em; color: #17324f; font-weight: 400; font-size: 3em; }
h4 { margin-bottom: 1em; font-weight: 400; font-size: 1.375em; }
p { margin-bottom: 1.5em; font-size: 1.125em; }
hr { margin: 2.5em 0; padding: 0; width: 100%; height: 3px; border: 0; background: #e6eaef; }
pre code { padding: 20px; border: 1px solid #EBEBEB; background: #F5F5F5; color: #08468a; font-weight: 200; font-size: .875em; }
code { background: transparent; color: #08468a; font-size: .875em; }
form { margin: 0; }
label { display: block; color: #18324f; font-weight: 400; font-size: 1.5em; margin-bottom: 2em; }
legend { position: static; margin: 0; padding: 0; font-weight: normal; }
legend span { position: absolute; top: 0; right: 0; left: 0; display: block; padding: 7px 0; border-bottom: 1px solid #e0dede; color: #ed4a21; font-size: 18px; line-height: 1em; }
/* Menu Sidebar*/
.button-block { padding-top: 15px; }
.button-block .btn-1 { margin-right: 6px; }
.btn, .spy-nav a { position: relative; display: inline-block; margin: 0; padding: 0 20px; height: 57px; border: 0; vertical-align: top; text-align: center; text-transform: uppercase; font-weight: 400; font-size: 1.125em; transitionP: all .2s; line-height: 57px; }
.btn.btn-action, .spy-nav a.btn-action { background: #ee2d4d; color: #fff; }
.btn.btn-action:hover, .spy-nav a.btn-action:hover { background: #bf0f2d; }
.btn.btn-default, .spy-nav a { background: #31811D; color: #fff; }
.btn.btn-default:hover, .spy-nav a:hover { background: #2F611C; color: #fff; }
.btn.btn-text, .spy-nav a.btn-text { color: #18324f; font-weight: 600; }
.btn.btn-full, .spy-nav a { display: block; }
@media only screen and (max-width: 480px) {
.site-header{ position: fixed !important; top: 0; z-index: 999999}
.page-title-wrapper{ margin-top: 70px;}
.main-wrapper iframe{ width: 42% !important; float: left; margin-left: 8%;}
.content iframe{width: 100%; height: 100%;}
}
.btn-top { position: relative; display: inline-block; float: right; margin: 20px 0 0; padding: 0 30px 0 50px; height: 57px; border: 2px solid ##31811D; color: #31811D; vertical-align: top; text-align: center; text-transform: uppercase; font-weight: 600; font-size: 1.125em; line-height: 53px; transition: all .2s; }
.btn-top:before { background-position: 0 -140px; width: 52px; height: 52px; position: absolute; top: 0; left: 0; content: ''; }
@media only screen and (min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 2) { .btn-top:before { background-position: 0 -140px; background-size: 152px auto; width: 52px; height: 52px; } }
.btn-top:hover { border-color: #2F611C; color: #2F611C; }
@media only screen and (max-width: 768px) { .btn-top { float: none; margin-top: 0; margin-bottom: 30px; white-space: nowrap; } }
@media only screen and (max-width: 480px) { .btn-top { font-size: 0.9em; line-height: 46px; height: 48px; padding-right: 22px; padding-left: 47px; } }
.btn-download { float: right; padding-left: 50px; }
.btn-download:before { background-position: -18px -116px; width: 16px; height: 16px; position: absolute; top: 50%; left: 20px; margin-top: -7px; content: ''; }
@media only screen and (min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 2) { .btn-download:before { background-position: -18px -116px; background-size: 152px auto; width: 16px; height: 16px; } }
.btn-done { float: right; padding-left: 50px; }
.btn-done:before { background-position: 0 -116px; width: 18px; height: 14px; position: absolute; top: 50%; margin-top: -7px; left: 20px; content: ''; }
@media only screen and (min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 2) { .btn-done:before { background-position: 0 -116px; background-size: 152px auto; width: 18px; height: 13.5px; margin-top: -6.75px; } }
.btn-cancel { float: right; }
*, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; }
html { -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; min-width: 280px; }
@media only screen and (min-width: 64.063em) and (max-width: 90em) { html { min-width: 960px; } }
body { font-size: 16px; font-family: 'Source Sans Pro', sans-serif; min-width: 290px; }
@media only screen and (max-width: 480px) { body.page-home { background-image: none; } }
img { max-width: 100%; height: auto !important; }
input { -webkit-appearance: none; -webkit-border-radius: 0; border-radius: 0; }
main { overflow: hidden; }
.clearfix:after { content: ""; display: table; clear: both; }
.container { width: 60em; margin-left: auto; margin-right: auto; }
.container:after { content: " "; display: block; clear: both; }
@media only screen and (max-width: 1024px) { .container { margin-left: 15px; margin-right: 15px; width: auto; } }
.content ul { padding-left: 19px; list-style-type: square; margin-top: 15px; }
/* Menu top */
.main-nav { float: right; }
.fixed-wrapper .main-nav { display: none; }
.active .main-nav { display: block; }
.main-nav > ul { list-style: none; }
.main-nav > ul > li { float: left; }
.main-nav > ul > li > a { display: block; padding: 22px 30px; color: #fff; text-decoration: none; text-transform: uppercase; font-weight: 600; font-size: 1.375em; line-height: 29px; transition: all .2s; }
.main-nav > ul > li > a:hover { color: #bfe5f1; background-color: #2F611C; }
.main-nav > ul > li > a.active { background-color: #2F611C; color: #fff; }
.main-nav > ul > li > a.opened { background-color: #18324f; }
@media only screen and (max-width: 600px) { .main-nav { font-size: 0.86em; }
.main-nav > ul > li > a { padding-left: 18px; padding-right: 18px; } }
@media only screen and (max-width: 480px) { .main-nav > ul > li > a { font-size: 0.95em; padding: 22px 6px; } }
.site-header { position: relative; width: 100%; background: #31811D; }
.site-header h1 { float: left; margin: 15px 0; }
.site-header h1 a { display: block; }
.site-header h1 img { display: block; max-height: 42px; }
@media only screen and (max-width: 480px) { .site-header h1 img { max-height: 42px; } }
.page-title-wrapper { position: relative; padding: 26px 0 55px; text-align: center; }
.page-title-wrapper .page-title { margin-top: 44px; color: #17324f; font-weight: 400; font-size: 3.75em; }
.page-title-wrapper .linguistics { padding: 0 2em 13px; border-bottom: 1px solid #D4DBE3; color: #18324f; text-transform: uppercase; font-weight: 400; font-size: 1.25em; }
@media only screen and (max-width: 768px) { .page-title-wrapper { font-size: 0.8em; } }
@media only screen and (max-width: 480px) { .page-title-wrapper { font-size: 0.65em; } }
.site-footer { margin-top: 20px; padding-top: 50px; padding-bottom: 50px; background: #18324f; color: #7c8ea3; text-align: center; }
.site-footer .container { position: relative; }
.site-footer + .bcms-clearfix:after { content: ""; }
.about + .site-footer .main { padding-top: 150px; }
.footer-logos ul li{ list-style: none; display: inline-block;}
.footer-logos ul li a{ padding-left: 10px; padding-right: 10px}
.site-footer a{ color: white !important;}
.site-footer p { text-align: left; display: block; margin-bottom: 1.5em; font-size: 1.125em; }
@media only screen and (max-width: 1024px) { .site-footer p { margin-left: 0; } }
@media only screen and (max-width: 768px) { .site-footer p { text-align: center; margin-left: auto; } }
@media only screen and (max-width: 600px) { .site-footer { font-size: 0.9em; } }
.main-logo { display: block; float: left; margin: 30px 0; }
.fixed-wrapper .main-logo { display: none; }
.main-logo img { display: block; }
.main-logo figure { position: relative; margin: 0; max-width: 56px; }
.main-logo figcaption { position: absolute; width: 160px; top: 20px; left: 68px; }
.active .main-logo { display: block; margin: 0; }
.active .main-logo figure { max-width: 42px; }
.active .main-logo figcaption { width: 120px; top: 15px; left: 55px; }
@media only screen and (max-width: 480px) { .main-logo figcaption { display: none; } }
.container { width: 60em; margin-left: auto; margin-right: auto; }
.container:after { content: " "; display: block; clear: both; }
@media only screen and (max-width: 1024px) { .container { margin-left: 15px; margin-right: 15px; width: auto; } }
.component-demo { position: relative; padding: 1px 0 0; background: #e6eaef; }
.component-demo:before { background-image: url("../img/enf.png"); }
@media only screen and (max-width: 480px) { .component-demo { padding: 40px 0 0; } }
.component-info .container { position: relative; }
.component-info .sidebar { width: 220px; float: left; margin-top: 75px; }
.component-info .sidebar .component-meta { margin-top: 10px; font-size: 1.125em; }
.component-info .sidebar .component-meta span { white-space: nowrap; margin-bottom: 10px; padding-left: 25px; color: #18324f; }
.component-info .sidebar.sticky { position: fixed; margin-top: 38px; }
.component-info .content { width: 64.58333333%; float: right; margin-top: 60px; margin-bottom: 75px; }
.component-info .content h3 { margin-bottom: .75em; font-size: 2.75em; }
.component-info .content p { margin-bottom: 1.75em; line-height: 1.45; }
@media only screen and (max-width: 480px) { .component-info .content .section-title { font-size: 2.1em; } }
@media only screen and (max-width: 768px) { .component-info .sidebar { float: none; margin-left: auto; margin-right: auto; }
.component-info .sidebar .component-meta { margin-top: 30px; text-align: center; }
.component-info .sidebar.sticky { position: relative; margin-top: 75px; }
.component-info .content { float: none; width: 100%; } }
@media only screen and (max-width: 480px) { .component-info .content { margin-bottom: 0; } }
.spy-nav { margin-bottom: 10px; }
.spy-nav ul { list-style: none; }
.spy-nav a { padding-top: 9px; padding-bottom: 10px; height: auto; border-bottom: 1px solid #4B8B20; text-align: left; text-transform: none; font-size: 1.375em; line-height: normal; }
.spy-nav .active a { border-bottom-color: #fff; background: #fff; color: #17324f; }
@media only screen and (max-width: 768px) { /*.spy-nav { display: none; } */}
.main-wrapper { margin: 44px auto 44px; max-width: 600px; }
.main-wrapper label { display: block; margin-bottom: .75em; color: #3f4e5e; font-size: 1.25em; }
.main-wrapper .text-field { padding: 0 15px; width: 100%; height: 40px; border: 1px solid #CBD3DD; font-size: 1.125em; }
.main-wrapper ::-webkit-input-placeholder { color: #CBD3DD; font-style: italic; font-size: 18px; }
.main-wrapper :-moz-placeholder { color: #CBD3DD; font-style: italic; font-size: 18px; }
.main-wrapper ::-moz-placeholder { color: #CBD3DD; font-style: italic; font-size: 18px; }
.main-wrapper :-ms-input-placeholder { color: #CBD3DD; font-style: italic; font-size: 18px; }
.page-icon-wrapper:before, .page-icon-wrapper .logo-asp:before, .page-icon-wrapper .logo-hibernate:before, .page-icon-wrapper .logo-angularjs:before, .page-icon-wrapper .logo-requirejs:before, .page-icon-wrapper .logo-reward:before, .component-demo:before {background-repeat: no-repeat; background-size: 100%; width: 92px; height: 108px; position: absolute; left: 50%; margin-left: -46px; top: 0; bottom: auto; margin-top: -28px; content: ''; }
.container { width: 60em; margin-left: auto; margin-right: auto; }
.container:after { content: " "; display: block; clear: both; }
@media only screen and (max-width: 1024px) { .container { margin-left: 15px; margin-right: 15px; width: auto; } }
.bcms-clearfix:after {content: ""; visibility: hidden; display: block; height: 0; clear: both; }

View File

@@ -1,97 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">Installation</h3>
<p>The suggested installation method is via <a href="https://getcomposer.org/" target="_blank">composer</a>.</p>
<pre><code class="sh">php composer.phar require ocramius/proxy-manager:1.0.*</code></pre>
<hr />
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

View File

@@ -1,314 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager - Ghost object</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php, ghost object" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">Lazy Loading Ghost Object Proxies</h3>
<p>A lazy loading ghost object proxy is a ghost proxy that looks exactly like the real instance of the proxied subject, but which has all properties nulled before initialization.</p>
<hr />
<h3 class="section-title">Lazy loading with the Ghost Object</h3>
<p>In pseudo-code, in userland, <a href="http://www.martinfowler.com/eaaCatalog/lazyLoad.html" target="_blank">lazy loading</a> in a ghost object looks like following:</p>
<pre>
<code class="php">
class MyObjectProxy
{
private $initialized = false;
private $name;
private $surname;
public function doFoo()
{
$this->init();
// Perform doFoo routine using loaded variables
}
private function init()
{
if (! $this->initialized) {
$data = some_logic_that_loads_data();
$this->name = $data['name'];
$this->surname = $data['surname'];
$this->initialized = true;
}
}
}
</code>
</pre>
<p>Ghost objects work similarly to virtual proxies, but since they don't wrap around a "real" instance of the proxied subject, they are better suited for representing dataset rows.</p>
<hr />
<h3 class="section-title">When do I use a ghost object?</h3>
<p>You usually need a ghost object in cases where following applies</p>
<ul>
<li>you are building a small data-mapper and want to lazily load data across associations in your object graph</li>
<li>you want to initialize objects representing rows in a large dataset</li>
<li>you want to compare instances of lazily initialized objects without the risk of comparing a proxy with a real subject</li>
<li>you are aware of the internal state of the object and are confident in working with its internals via reflection or direct property access</li>
</ul>
<hr />
<h3 class="section-title">Usage examples</h3>
<p><a href="https://github.com/Ocramius/ProxyManager" target="_blank">ProxyManager</a> provides a factory that creates lazy loading ghost objects. To use it, follow these steps:</p>
<p>First of all, define your object's logic without taking care of lazy loading:</p>
<pre>
<code class="php">
namespace MyApp;
class Customer
{
private $name;
private $surname;
// just write your business logic or generally logic
// don't worry about how complex this object will be!
// don't code lazy-loading oriented optimizations in here!
public function getName() { return $this->name; }
public function setName($name) { $this->name = (string) $name; }
public function getSurname() { return $this->surname; }
public function setSurname($surname) { $this->surname = (string) $surname; }
}
</code>
</pre>
<p>Then use the proxy manager to create a ghost object of it. You will be responsible of setting its state during lazy loading:</p>
<pre>
<code class="php">
namespace MyApp;
use ProxyManager\Factory\LazyLoadingGhostFactory;
use ProxyManager\Proxy\LazyLoadingInterface;
require_once __DIR__ . '/vendor/autoload.php';
$factory = new LazyLoadingGhostFactory();
$initializer = function (LazyLoadingInterface $proxy, $method, array $parameters, & $initializer) {
$initializer = null; // disable initialization
// load data and modify the object here
$proxy->setName('Agent');
$proxy->setSurname('Smith');
return true; // confirm that initialization occurred correctly
};
$instance = $factory->createProxy('MyApp\Customer', $initializer);
</code>
</pre>
<p>You can now simply use your object as before:</p>
<pre>
<code class="php">
// this will just work as before
echo $proxy->getName() . ' ' . $proxy->getSurname(); // Agent Smith
</code>
</pre>
<hr />
<h3 class="section-title">Lazy Initialization</h3>
<p>As you can see, we use a closure to handle lazy initialization of the proxy instance at runtime. The initializer closure signature for ghost objects should be as following:</p>
<pre>
<code class="php">
/**
* @var object $proxy the instance the ghost object proxy that is being initialized
* @var string $method the name of the method that triggered lazy initialization
* @var array $parameters an ordered list of parameters passed to the method that
* triggered initialization, indexed by parameter name
* @var Closure $initializer a reference to the property that is the initializer for the
* proxy. Set it to null to disable further initialization
*
* @return bool true on success
*/
$initializer = function ($proxy, $method, $parameters, &amp; $initializer) {};
</code>
</pre>
<p>The initializer closure should usually be coded like following:</p>
<pre>
<code class="php">
$initializer = function ($proxy, $method, $parameters, & $initializer) {
$initializer = null; // disable initializer for this proxy instance
// modify the object with loaded data
$proxy->setFoo(/* ... */);
$proxy->setBar(/* ... */);
return true; // report success
};
</code>
</pre>
<p>The <code>ProxyManager\Factory\LazyLoadingGhostFactory</code> produces proxies that implement both the <code>ProxyManager\Proxy\GhostObjectInterface</code> and the <code>ProxyManager\Proxy\LazyLoadingInterface</code>.</p>
<p>At any point in time, you can set a new initializer for the proxy:</p>
<pre>
<code class="php">
$proxy->setProxyInitializer($initializer);
</code>
</pre>
<p>In your initializer, you <strong>MUST</strong> turn off any further initialization:</p>
<pre>
<code class="php">
$proxy->setProxyInitializer(null);
</code>
</pre>
<p>or</p>
<pre>
<code class="php">
$initializer = null; // if you use the initializer passed by reference to the closure
</code>
</pre>
<hr />
<h3 class="section-title">Triggering Initialization</h3>
<p>A lazy loading ghost object is initialized whenever you access any property or method of it. Any of the following interactions would trigger lazy initialization:</p>
<pre>
<code class="php">
// calling a method
$proxy->someMethod();
// reading a property
echo $proxy->someProperty;
// writing a property
$proxy->someProperty = 'foo';
// checking for existence of a property
isset($proxy->someProperty);
// removing a property
unset($proxy->someProperty);
// cloning the entire proxy
clone $proxy;
// serializing the proxy
$unserialized = unserialize(serialize($proxy));
</code>
</pre>
<p>Remember to call <code>$proxy->setProxyInitializer(null);</code> to disable initialization of your proxy, or it will happen more than once.</p>
<hr />
<h3 class="section-title">Proxying interfaces</h3>
<p>You can also generate proxies from an interface FQCN. By proxying an interface, you will only be able to access the methods defined by the interface itself, even if the <code>wrappedObject</code> implements more methods. This will anyway save some memory since the proxy won't contain any properties.</p>
<p>Tuning performance for production</p>
<p>See <a href="production.html">Tuning ProxyManager for Production.</a></p>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

View File

@@ -1,295 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content"><div class="page-title-wrapper">
<div class="container">
<img src="https://github.com/Ocramius/ProxyManager/raw/master/proxy-manager.png">
<h2 class="page-title">Proxy Manager</h2>
</div>
</div>
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<h3>Proxy Manager</h3>
<p>This library aims at providing abstraction for generating various kinds of <a href="http://ocramius.github.io/presentations/proxy-pattern-in-php/" target="_blank">proxy classes</a>.</p>
<p>If you want to learn more about proxy pattern watch this video:</p>
<iframe width="640" height="390" src="//www.youtube.com/embed/Ka8wlV8M6Vg" frameborder="0" allowfullscreen></iframe>
<hr />
<div class="bcms-clearfix"></div>
<h3 class="section-title">Installation</h3>
<p>The suggested installation method is via <a href="https://getcomposer.org/" target="_blank">composer</a>.</p>
<pre><code class="sh">php composer.phar require ocramius/proxy-manager:1.0.*</code></pre>
<hr />
<h3 class="section-title" id="virtualproxy">Lazy Loading Value Holders (Virtual Proxy)</h3>
<p>ProxyManager can generate
<a href="http://www.martinfowler.com/eaaCatalog/lazyLoad.html" target="_blank">lazy loading value holders</a>,
which are virtual proxies capable of saving performance and memory for objects that
require a lot of dependencies or CPU cycles to be loaded:
particularly useful when you may not always need the object,
but are constructing it anyways.</p>
<pre>
<code class="php">
$factory = new \ProxyManager\Factory\LazyLoadingValueHolderFactory();
$proxy = $factory->createProxy(
'MyApp\HeavyComplexObject',
function (&amp; $wrappedObject, $proxy, $method, $parameters, &amp; $initializer) {
$wrappedObject = new HeavyComplexObject(); // instantiation logic here
$initializer = null; // turning off further lazy initialization
return true;
}
);
$proxy->doFoo();
</code>
</pre>
<p>See the <a href="virtual-proxy.html">complete documentation about lazy loading value holders</a>.</p>
<hr />
<h3 class="section-title">Access Interceptor Value Holder</h3>
<p>An access interceptor value holder is a smart reference that allows you to execute
logic before and after a particular method is executed or a particular property is
accessed, and it allows to manipulate parameters and return values depending on
your needs.</p>
<pre>
<code class="php">
$factory = new \ProxyManager\Factory\AccessInterceptorValueHolderFactory();
$proxy = $factory->createProxy(
new \My\Db\Connection(),
array('query' => function () { echo "Query being executed!\n"; }),
array('query' => function () { echo "Query completed!\n"; })
);
$proxy->query(); // produces "Query being executed!\nQuery completed!\n"
</code>
</pre>
<p>See the <a href="access-interceptor-value-holder-proxy.html">complete documentation about access interceptor value holders</a>.</p>
<hr />
<h3 class="section-title">Access Interceptor Scope Localizer</h3>
<p>An access interceptor scope localizer works exactly like an access interceptor
value holder, but it is safe to use to proxy fluent interfaces.</p>
<p>See the <a href="access-interceptor-scope-localizer-proxy.html">complete documentation about access interceptor scope localizer</a>.</p>
<hr />
<h3 class="section-title">Null Objects</h3>
<p>A Null Object proxy implements the null object pattern.</p>
<p>This kind of proxy allows you to have fallback logic in case loading of the wrapped value failed.</p>
<pre>
<code class="php">
$factory = new \ProxyManager\Factory\NullObjectFactory();
$proxy = $factory->createProxy('My\EntityObject');
$proxy->getName(); // empty return
</code>
</pre>
<p>A Null Object Proxy can be created from an object, a class name or an interface name:</p>
<pre>
<code class="php">
$factory = new \ProxyManager\Factory\NullObjectFactory();
$proxy = $factory->createProxy('My\EntityObjectInterface');
$proxy->getName(); // empty return
$proxy = $factory->createProxy($entity); // created from object
$proxy->getName(); // empty return
</code>
</pre>
<p>See the <a href="null-object.html">complete documentation about null object proxy</a>.</p>
<hr />
<h3 class="section-title">Ghost Objects</h3>
<p>Similar to value holder, a ghost object is usually created to handle lazy loading.</p>
<p>The difference between a value holder and a ghost object is that the ghost
object does not contain a real instance of the required object, but handles
lazy loading by initializing its own inherited properties.</p>
<p>ProxyManager can generate
<a href="http://www.martinfowler.com/eaaCatalog/lazyLoad.html" target="_blank">lazy loading ghost objects</a>,
which are proxies used to save performance and memory for large datasets and
graphs representing relational data. Ghost objects are particularly useful
when building data-mappers.</p>
<p>Additionally, the overhead introduced by ghost objects is very low when
compared to the memory and performance overhead caused by virtual proxies.</p>
<pre>
<code class="php">
$factory = new \ProxyManager\Factory\LazyLoadingGhostFactory();
$proxy = $factory->createProxy(
'MyApp\HeavyComplexObject',
function ($proxy, $method, $parameters, & $initializer) {
$initializer = null; // turning off further lazy initialization
// modify the proxy instance
$proxy->setFoo('foo');
$proxy->setBar('bar');
return true;
}
);
$proxy->doFoo();
</code>
</pre>
<p>See the <a href="ghost-object.html">complete documentation about lazy loading ghost objects</a>.</p>
<hr />
<h3 class="section-title">Remote Object</h3>
<p>A remote object proxy is an object that is located on a different system,
but is used as if it was available locally. There's various possible
remote proxy implementations, which could be based on xmlrpc/jsonrpc/soap/dnode/etc.</p>
<p>This example uses the XML-RPC client of Zend Framework 2:</p>
<pre>
<code class="php">
interface FooServiceInterface
{
public function foo();
}
$factory = new \ProxyManager\Factory\RemoteObjectFactory(
new \ProxyManager\Factory\RemoteObject\Adapter\XmlRpc(
new \Zend\XmlRpc\Client('https://example.com/rpc-endpoint')
)
);
// proxy is your remote implementation
$proxy = $factory->createProxy('FooServiceInterface');
var_dump($proxy->foo());
</code>
</pre>
<p>See the <a href="remote-object.html">complete documentation about remote objects</a>.</p>
<hr />
<h3 class="section-title">Contributing</h3>
<p>Please read the <a href="contributing.html">CONTRIBUTING</a> contents if you wish to help out!</p>
<hr />
<h3 class="section-title">Credits</h3>
<p>The idea was originated by a <a href="http://marco-pivetta.com/proxy-pattern-in-php/" target="_blank">talk about Proxies in PHP OOP</a> that I gave at the <a href="https://twitter.com/phpugffm" target="_blank">@phpugffm</a> in January 2013.</p>
<div class="bcms-clearfix"></div>
</div>
</div>
</div>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

View File

@@ -1,185 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager - Null object</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php, null object" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">Null Object Proxy</h3>
<p>A Null Object proxy is a <a href="http://en.wikipedia.org/wiki/Null_Object_pattern" target="_blank">null object pattern</a> implementation. The proxy factory creates a new object with defined neutral behavior based on an other object, class name or interface.</p>
<hr />
<h3 class="section-title">What is null object proxy ?</h3>
<p>In your application, when you can't return the object related to the request, the consumer of the model must check for the return value and handle the failing condition gracefully, thus generating an explosion of conditionals throughout your code. Fortunately, this seemingly-tangled situation can be sorted out simply by creating a polymorphic implementation of the domain object, which would implement the same interface as the one of the object in question, only that its methods wouldnt do anything, therefore offloading client code from doing repetitive checks for ugly null values when the operation is executed.</p>
<hr />
<h3 class="section-title">Usage examples</h3>
<pre>
<code class="php">
class UserMapper
{
private $adapter;
public function __construct(DatabaseAdapterInterface $adapter) {
$this->adapter = $adapter;
}
public function fetchById($id) {
$this->adapter->select("users", array("id" => $id));
if (!$row = $this->adapter->fetch()) {
return null;
}
return $this->createUser($row);
}
private function createUser(array $row) {
$user = new Entity\User($row["name"], $row["email"]);
$user->setId($row["id"]);
return $user;
}
}
</code>
</pre>
<p>If you want to remove conditionals from client code, you need to have a version of the entity conforming to the corresponding interface. With the Null Object Proxy, you can build this object :</p>
<pre>
<code class="php">
$factory = new \ProxyManager\Factory\NullObjectFactory();
$nullUser = $factory->createProxy('Entity\User');
var_dump($nullUser->getName()); // empty return
</code>
</pre>
<p>You can now return a valid entity :</p>
<pre>
<code class="php">
class UserMapper
{
private $adapter;
public function __construct(DatabaseAdapterInterface $adapter) {
$this->adapter = $adapter;
}
public function fetchById($id) {
$this->adapter->select("users", array("id" => $id));
return $this->createUser($this->adapter->fetch());
}
private function createUser($row) {
if (!$row) {
$factory = new \ProxyManager\Factory\NullObjectFactory();
return $factory->createProxy('Entity\User');
}
$user = new Entity\User($row["name"], $row["email"]);
$user->setId($row["id"]);
return $user;
}
}
</code>
</pre>
<hr />
<h3 class="section-title">Proxying interfaces</h3>
<p>You can also generate proxies from an interface FQCN. By proxying an interface, you will only be able to access the methods defined by the interface itself, and like with the object, the methods are empty.</p>
<p>Tuning performance for production</p>
<p>See <a href="production.html">Tuning ProxyManager for Production.</a></p>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

View File

@@ -1,114 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager - Tuning the ProxyManager for production</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php, production" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">Tuning the ProxyManager for production</h3>
<p>By default, all proxy factories generate the required proxy classes at runtime.</p>
<p>Proxy generation causes I/O operations and uses a lot of reflection, so be sure to have generated all of your proxies <strong>before deploying your code on a live system</strong>, or you may experience poor performance.</p>
<p>You can configure ProxyManager so that it will try autoloading the proxies first. Generating them "bulk" is not yet implemented:</p>
<pre>
<code class="php">
$config = new \ProxyManager\Configuration();
$config->setProxiesTargetDir(__DIR__ . '/my/generated/classes/cache/dir');
// then register the autoloader
spl_autoload_register($config->getProxyAutoloader());
</code>
</pre>
<p>Generating a classmap with all your proxy classes in it will also work perfectly.</p>
<p>Please note that all the currently implemented <code>ProxyManager\Factory\*</code> classes accept a <code>ProxyManager\Configuration</code> object as optional constructor parameter. This allows for fine-tuning of ProxyManager according to your needs.</p>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

View File

@@ -1,203 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager - Remote object</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php, remote object" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">Remote Object Proxy</h3>
<p>The remote object implementation is a mechanism that enables an local object to control an other object on an other server. Each call method on the local object will do a network call to get information or execute operations on the remote object.</p>
<hr />
<h3 class="section-title">What is remote object proxy ?</h3>
<p>A remote object is based on an interface. The remote interface defines the API that a consumer can call. This interface must be implemented both by the client and the RPC server.</p>
<hr />
<h3 class="section-title">Adapters</h3>
<p>ZendFramework's RPC components (XmlRpc, JsonRpc &amp; Soap) can be used easily with the remote object. You will need to require the one you need via composer, though:</p>
<pre>
<code class="sh">
$ php composer.phar require zendframework/zend-xmlrpc:2.*
$ php composer.phar require zendframework/zend-json:2.*
$ php composer.phar require zendframework/zend-soap:2.*
</code>
</pre>
<p>ProxyManager comes with 3 adapters:</p>
<ul>
<li><code>ProxyManager\Factory\RemoteObject\Adapter\XmlRpc</code></li>
<li><code>ProxyManager\Factory\RemoteObject\Adapter\JsonRpc</code></li>
<li><code>ProxyManager\Factory\RemoteObject\Adapter\Soap</code></li>
</ul>
<hr />
<h3 class="section-title">Usage examples</h3>
<p>RPC server side code (<code>xmlrpc.php</code> in your local webroot):</p>
<pre>
<code class="php">
interface FooServiceInterface
{
public function foo();
}
class Foo implements FooServiceInterface
{
/**
* Foo function
* @return string
*/
public function foo()
{
return 'bar remote';
}
}
$server = new Zend\XmlRpc\Server();
$server->setClass('Foo', 'FooServiceInterface'); // my FooServiceInterface implementation
$server->handle();
</code>
</pre>
<p>Client side code (proxy) :</p>
<pre>
<code class="php">
interface FooServiceInterface
{
public function foo();
}
$factory = new \ProxyManager\Factory\RemoteObjectFactory(
new \ProxyManager\Factory\RemoteObject\Adapter\XmlRpc(
new \Zend\XmlRpc\Client('https://localhost/xmlrpc.php')
)
);
$proxy = $factory->createProxy('FooServiceInterface');
var_dump($proxy->foo()); // "bar remote"
</code>
</pre>
<hr />
<h3 class="section-title">Implementing custom adapters</h3>
<p>Your adapters must implement <code>ProxyManager\Factory\RemoteObject\AdapterInterface</code> :</p>
<pre>
<code class="php">
interface AdapterInterface
{
/**
* Call remote object
*
* @param string $wrappedClass
* @param string $method
* @param array $params
*
* @return mixed
*/
public function call($wrappedClass, $method, array $params = array());
}
</code>
</pre>
<p>It is very easy to create your own implementation (for RESTful web services, for example). Simply pass your own adapter instance to your factory at construction time</p>
<p>Tuning performance for production</p>
<p>See <a href="production.html">Tuning ProxyManager for Production.</a></p>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

View File

@@ -1,305 +0,0 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager - Virtual Proxy</title>
<meta name="description" content="A proxyManager write in php" />
<meta name="keywords" content="ProxyManager, proxy, manager, ocramius, Marco Pivetta, php, virtual proxy" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="index.html"><img alt="ProxyManager" src="img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a>
<div class="bcms-clearfix"></div>
</li>
</ul>
</nav>
</div>
</header>
<main role="main">
<section class="component-content">
<div class="component-demo" id="live-demo">
<div class="container">
<div class="main-wrapper" style="text-align: right">
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=fork&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="310" height="40"></iframe>
<iframe src="http://ghbtns.com/github-btn.html?user=ocramius&amp;repo=ProxyManager&amp;type=watch&amp;count=true&amp;size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="40"></iframe>
</div>
<div class="bcms-clearfix bcms-clearfix"></div>
</div>
</div>
<div class="component-info">
<div class="container">
<aside class="sidebar">
<nav class="spy-nav">
<ul>
<li><a href="index.html">Intro</a></li>
<li><a href="virtual-proxy.html">Virtual Proxy</a></li>
<li><a href="null-object.html">Null Objects</a></li>
<li><a href="ghost-object.html">Ghost Objects</a></li>
<li><a href="remote-object.html">Remote Object</a></li>
<li><a href="contributing.html">Contributing</a></li>
<li><a href="credits.html">Credits</a></li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
<div class="bcms-clearfix"></div>
<h3 class="section-title">Lazy Loading Value Holder Proxy</h3>
<p>A lazy loading value holder proxy is a virtual proxy that wraps and lazily initializes a "real" instance of the proxied class.</p>
<hr />
<h3 class="section-title">What is lazy loading?</h3>
<p>In pseudo-code, in userland, <a href="http://www.martinfowler.com/eaaCatalog/lazyLoad.html" target="_blank">lazy loading</a> looks like following:</p>
<pre>
<code class="php">
class MyObjectProxy
{
private $wrapped;
public function doFoo()
{
$this->init();
return $this->wrapped->doFoo();
}
private function init()
{
if (null === $this->wrapped) {
$this->wrapped = new MyObject();
}
}
}
</code>
</pre>
<p>This code is problematic, and adds a lot of complexity that makes your unit tests' code even worse.</p>
<p>Also, this kind of usage often ends up in coupling your code with a particular <a href="http://martinfowler.com/articles/injection.html" target="_blank">Dependency Injection Container</a> or a framework that fetches dependencies for you. That way, further complexity is introduced, and some problems related with service location raise, as I've explained <a href="http://ocramius.github.io/blog/zf2-and-symfony-service-proxies-with-doctrine-proxies/" target="_blank">in this article</a>.</p>
<p>Lazy loading value holders abstract this logic for you, hiding your complex, slow, performance-impacting objects behind tiny wrappers that have their same API, and that get initialized at first usage.</p>
<hr />
<h3 class="section-title">When do I use a lazy value holder?</h3>
<p>You usually need a lazy value holder in cases where following applies</p>
<ul>
<li>your object takes a lot of time and memory to be initialized (with all dependencies)</li>
<li>your object is not always used, and the instantiation overhead can be avoided</li>
</ul>
<hr />
<h3 class="section-title">Usage examples</h3>
<p>ProxyManager provides a factory that eases instantiation of lazy loading value holders. To use it, follow these steps:</p>
<p>First of all, define your object's logic without taking care of lazy loading:</p>
<pre>
<code class="php">
namespace MyApp;
class HeavyComplexObject
{
public function __construct()
{
// just write your business logic
// don't worry about how heavy initialization of this will be!
}
public function doFoo() {
echo "OK!"
}
}
</code>
</pre>
<p>Then use the proxy manager to create a lazy version of the object (as a proxy):</p>
<pre>
<code class="php">
namespace MyApp;
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use ProxyManager\Proxy\LazyLoadingInterface;
require_once __DIR__ . '/vendor/autoload.php';
$factory = new LazyLoadingValueHolderFactory();
$initializer = function (& $wrappedObject, LazyLoadingInterface $proxy, $method, array $parameters, & $initializer) {
$initializer = null; // disable initialization
$wrappedObject = new HeavyComplexObject(); // fill your object with values here
return true; // confirm that initialization occurred correctly
};
$instance = $factory->createProxy('MyApp\HeavyComplexObject', $initializer);
</code>
</pre>
<p>You can now simply use your object as before:</p>
<pre>
<code class="php">
// this will just work as before
$proxy->doFoo(); // OK!
</code>
</pre>
<hr />
<h3 class="section-title">Lazy Initialization</h3>
<p>As you can see, we use a closure to handle lazy initialization of the proxy instance at runtime. The initializer closure signature should be as following:</p>
<pre>
<code class="php">
/**
* @var object $wrappedObject the instance (passed by reference) of the wrapped object,
* set it to your real object
* @var object $proxy the instance proxy that is being initialized
* @var string $method the name of the method that triggered lazy initialization
* @var string $parameters an ordered list of parameters passed to the method that
* triggered initialization, indexed by parameter name
* @var Closure $initializer a reference to the property that is the initializer for the
* proxy. Set it to null to disable further initialization
*
* @return bool true on success
*/
$initializer = function (& $wrappedObject, $proxy, $method, $parameters, & $initializer) {};
</code>
</pre>
<p>The initializer closure should usually be coded like following:</p>
<pre>
<code class="php">
$initializer = function (& $wrappedObject, $proxy, $method, $parameters, & $initializer) {
$newlyCreatedObject = new Foo(); // instantiation logic
$newlyCreatedObject->setBar('baz') // instantiation logic
$newlyCreatedObject->setBat('bam') // instantiation logic
$wrappedObject = $newlyCreatedObject; // set wrapped object in the proxy
$initializer = null; // disable initializer
return true; // report success
};
</code>
</pre>
<p>The <code>ProxyManager\Factory\LazyLoadingValueHolderFactory</code> produces proxies that implement both the <code>ProxyManager\Proxy\ValueHolderInterface</code> and the <code>ProxyManager\Proxy\LazyLoadingInterface</code>.</p>
<p>At any point in time, you can set a new initializer for the proxy:</p>
<pre><code class="php">$proxy->setProxyInitializer($initializer);</code></pre>
<p>In your initializer, you currently <strong>MUST</strong> turn off any further initialization:</p>
<pre><code class="php">$proxy->setProxyInitializer(null);</code></pre>
<p>or</p>
<pre><code class="php">$initializer = null; // if you use the initializer by reference</code></pre>
<hr />
<h3 class="section-title">Triggering Initialization</h3>
<p>A lazy loading proxy is initialized whenever you access any property or method of it. Any of the following interactions would trigger lazy initialization:</p>
<pre>
<code class="php">
// calling a method
$proxy->someMethod();
// reading a property
echo $proxy->someProperty;
// writing a property
$proxy->someProperty = 'foo';
// checking for existence of a property
isset($proxy->someProperty);
// removing a property
unset($proxy->someProperty);
// cloning the entire proxy
clone $proxy;
// serializing the proxy
$unserialized = serialize(unserialize($proxy));
</code>
</pre>
<p>Remember to call <code>$proxy->setProxyInitializer(null);</code> to disable initialization of your proxy, or it will happen more than once.</p>
<hr />
<h3 class="section-title">Proxying interfaces</h3>
<p>You can also generate proxies from an interface FQCN. By proxying an interface, you will only be able to access the methods defined by the interface itself, even if the wrappedObject implements more methods. This will anyway save some memory since the proxy won't contain useless inherited properties.</p>
<p>Tuning performance for production</p>
<p>See <a href="production.html">Tuning ProxyManager for Production.</a></p>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="index.html">Intro</a> | </li>
<li><a href="virtual-proxy.html">Virtual Proxy</a> | </li>
<li><a href="null-object.html">Null Objects</a> | </li>
<li><a href="ghost-object.html">Ghost Objects</a> | </li>
<li><a href="remote-object.html">Remote Object</a> | </li>
<li><a href="contributing.html">Contributing</a> | </li>
<li><a href="credits.html">Credits</a> | </li>
<li><a href="copyright.html">Copyright</a></li>
</ul>
</div>
</div>
<div class="bcms-clearfix"></div>
</footer>
<div class="bcms-clearfix"></div>
</body>
</html>

View File

@@ -1,11 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0;URL=html-docs/">
<title></title>
</head>
<body>
</body>
</html>

View File

@@ -1,16 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<phpdox xmlns="http://phpdox.de/config" silent="false">
<project
name="ProxyManager"
source="src"
workdir="build/phpdox"
>
<collector publiconly="false">
<include mask="*.php" />
</collector>
<generator output="build">
<build engine="html" enabled="true" output="api"/>
</generator>
</project>
</phpdox>

View File

@@ -1,16 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<ruleset
name="ProxyManager rules"
xmlns="http://pmd.sf.net/ruleset/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd"
>
<rule ref="rulesets/codesize.xml"/>
<rule ref="rulesets/unusedcode.xml"/>
<rule ref="rulesets/design.xml">
<!-- eval is needed to generate runtime classes -->
<exclude name="EvalExpression"/>
</rule>
<rule ref="rulesets/naming.xml"/>
</ruleset>

View File

@@ -1,25 +0,0 @@
<?xml version="1.0"?>
<phpunit
bootstrap="./vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
verbose="true"
stopOnFailure="false"
processIsolation="false"
backupGlobals="false"
syntaxCheck="true"
>
<testsuite name="ProxyManager tests">
<directory>./tests/ProxyManagerTest</directory>
</testsuite>
<testsuite name="ProxyManager language integration tests">
<directory suffix=".phpt">./tests/language-feature-scripts</directory>
</testsuite>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
</phpunit>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

View File

@@ -1,46 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManager\Factory;
use Closure;
/**
* Base factory common logic
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
abstract class AbstractLazyFactory extends AbstractBaseFactory
{
/**
* Creates a new lazy proxy instance of the given class with
* the given initializer
*
* @param string $className name of the class to be proxied
* @param \Closure $initializer initializer to be passed to the proxy
*
* @return \ProxyManager\Proxy\LazyLoadingInterface
*/
public function createProxy($className, Closure $initializer)
{
$proxyClassName = $this->generateProxy($className);
return new $proxyClassName($initializer);
}
}

View File

@@ -1,149 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManager\Generator;
use ReflectionException;
use Zend\Code\Generator\ParameterGenerator as ZendParameterGenerator;
use Zend\Code\Generator\ValueGenerator;
use Zend\Code\Reflection\ParameterReflection;
/**
* Parameter generator that ensures that the parameter type is a FQCN when it is a class
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class ParameterGenerator extends ZendParameterGenerator
{
/**
* @override - uses `static` to instantiate the parameter
*
* {@inheritDoc}
*/
public static function fromReflection(ParameterReflection $reflectionParameter)
{
/* @var $param self */
$param = new static();
$param->setName($reflectionParameter->getName());
$param->setPosition($reflectionParameter->getPosition());
$type = self::extractParameterType($reflectionParameter);
if (null !== $type) {
$param->setType($type);
}
self::setOptionalParameter($param, $reflectionParameter);
$param->setPassedByReference($reflectionParameter->isPassedByReference());
return $param;
}
/**
* Retrieves the type of a reflection parameter (null if none is found)
*
* @param ParameterReflection $reflectionParameter
*
* @return string|null
*/
private static function extractParameterType(ParameterReflection $reflectionParameter)
{
if ($reflectionParameter->isArray()) {
return 'array';
}
if (method_exists($reflectionParameter, 'isCallable') && $reflectionParameter->isCallable()) {
return 'callable';
}
if ($typeClass = $reflectionParameter->getClass()) {
return $typeClass->getName();
}
return null;
}
/**
* @return string
*/
public function generate()
{
return $this->getGeneratedType()
. (true === $this->passedByReference ? '&' : '')
. '$' . $this->name
. $this->generateDefaultValue();
}
/**
* @return string
*/
private function generateDefaultValue()
{
if (null === $this->defaultValue) {
return '';
}
$defaultValue = $this->defaultValue instanceof ValueGenerator
? $this->defaultValue
: new ValueGenerator($this->defaultValue);
$defaultValue->setOutputMode(ValueGenerator::OUTPUT_SINGLE_LINE);
return ' = ' . $defaultValue;
}
/**
* Retrieves the generated parameter type
*
* @return string
*/
private function getGeneratedType()
{
if (! $this->type || in_array($this->type, static::$simple)) {
return '';
}
if ('array' === $this->type || 'callable' === $this->type) {
return $this->type . ' ';
}
return '\\' . trim($this->type, '\\') . ' ';
}
/**
* Set the default value for a parameter (if it is optional)
*
* @param ZendParameterGenerator $parameterGenerator
* @param ParameterReflection $reflectionParameter
*/
private static function setOptionalParameter(
ZendParameterGenerator $parameterGenerator,
ParameterReflection $reflectionParameter
) {
if ($reflectionParameter->isOptional()) {
try {
$parameterGenerator->setDefaultValue($reflectionParameter->getDefaultValue());
} catch (ReflectionException $e) {
$parameterGenerator->setDefaultValue(null);
}
}
}
}

View File

@@ -1,92 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ProxyManager\Exception\UnsupportedProxiedClassException;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\Generator\ParameterGenerator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* The `__construct` implementation for lazy loading proxies
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class Constructor extends MethodGenerator
{
/**
* Constructor
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct('__construct');
$localizedObject = new ParameterGenerator('localizedObject');
$prefix = new ParameterGenerator('prefixInterceptors');
$suffix = new ParameterGenerator('suffixInterceptors');
$localizedObject->setType($originalClass->getName());
$prefix->setDefaultValue(array());
$suffix->setDefaultValue(array());
$prefix->setType('array');
$suffix->setType('array');
$this->setParameter($localizedObject);
$this->setParameter($prefix);
$this->setParameter($suffix);
$localizedProperties = array();
foreach ($originalClass->getProperties() as $originalProperty) {
if ((! method_exists('Closure', 'bind')) && $originalProperty->isPrivate()) {
// @codeCoverageIgnoreStart
throw UnsupportedProxiedClassException::unsupportedLocalizedReflectionProperty($originalProperty);
// @codeCoverageIgnoreEnd
}
$propertyName = $originalProperty->getName();
if ($originalProperty->isPrivate()) {
$localizedProperties[] = "\\Closure::bind(function () use (\$localizedObject) {\n "
. '$this->' . $propertyName . ' = & $localizedObject->' . $propertyName . ";\n"
. '}, $this, ' . var_export($originalProperty->getDeclaringClass()->getName(), true)
. ')->__invoke();';
} else {
$localizedProperties[] = '$this->' . $propertyName . ' = & $localizedObject->' . $propertyName . ";";
}
}
$this->setDocblock(
"@override constructor to setup interceptors\n\n"
. "@param \\" . $originalClass->getName() . " \$localizedObject\n"
. "@param \\Closure[] \$prefixInterceptors method interceptors to be used before method logic\n"
. "@param \\Closure[] \$suffixInterceptors method interceptors to be used before method logic"
);
$this->setBody(
(empty($localizedProperties) ? '' : implode("\n\n", $localizedProperties) . "\n\n")
. '$this->' . $prefixInterceptors->getName() . " = \$prefixInterceptors;\n"
. '$this->' . $suffixInterceptors->getName() . " = \$suffixInterceptors;"
);
}
}

View File

@@ -1,79 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\Generator\ParameterGenerator;
use ReflectionClass;
use ReflectionProperty;
use Zend\Code\Generator\PropertyGenerator;
/**
* The `__construct` implementation for lazy loading proxies
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class Constructor extends MethodGenerator
{
/**
* Constructor
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $valueHolder,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct('__construct');
$prefix = new ParameterGenerator('prefixInterceptors');
$suffix = new ParameterGenerator('suffixInterceptors');
$prefix->setDefaultValue(array());
$suffix->setDefaultValue(array());
$prefix->setType('array');
$suffix->setType('array');
$this->setParameter(new ParameterGenerator('wrappedObject'));
$this->setParameter($prefix);
$this->setParameter($suffix);
/* @var $publicProperties \ReflectionProperty[] */
$publicProperties = $originalClass->getProperties(ReflectionProperty::IS_PUBLIC);
$unsetProperties = array();
foreach ($publicProperties as $publicProperty) {
$unsetProperties[] = '$this->' . $publicProperty->getName();
}
$this->setDocblock(
"@override constructor to setup interceptors\n\n"
. "@param \\" . $originalClass->getName() . " \$wrappedObject\n"
. "@param \\Closure[] \$prefixInterceptors method interceptors to be used before method logic\n"
. "@param \\Closure[] \$suffixInterceptors method interceptors to be used before method logic"
);
$this->setBody(
($unsetProperties ? 'unset(' . implode(', ', $unsetProperties) . ");\n\n" : '')
. '$this->' . $valueHolder->getName() . " = \$wrappedObject;\n"
. '$this->' . $prefixInterceptors->getName() . " = \$prefixInterceptors;\n"
. '$this->' . $suffixInterceptors->getName() . " = \$suffixInterceptors;"
);
}
}

View File

@@ -1,58 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManager\ProxyGenerator\LazyLoading\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\Generator\ParameterGenerator;
use ReflectionClass;
use ReflectionProperty;
use Zend\Code\Generator\PropertyGenerator;
/**
* The `__construct` implementation for lazy loading proxies
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class Constructor extends MethodGenerator
{
/**
* Constructor
*/
public function __construct(ReflectionClass $originalClass, PropertyGenerator $initializerProperty)
{
parent::__construct('__construct');
$this->setParameter(new ParameterGenerator('initializer'));
/* @var $publicProperties \ReflectionProperty[] */
$publicProperties = $originalClass->getProperties(ReflectionProperty::IS_PUBLIC);
$unsetProperties = array();
foreach ($publicProperties as $publicProperty) {
$unsetProperties[] = '$this->' . $publicProperty->getName();
}
$this->setDocblock("@override constructor for lazy initialization\n\n@param \\Closure|null \$initializer");
$this->setBody(
($unsetProperties ? 'unset(' . implode(', ', $unsetProperties) . ");\n\n" : '')
. '$this->' . $initializerProperty->getName() . ' = $initializer;'
);
}
}

View File

@@ -1,71 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManager\ProxyGenerator\LazyLoadingGhost\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use Zend\Code\Generator\MethodGenerator as ZendMethodGenerator;
use Zend\Code\Generator\PropertyGenerator;
use Zend\Code\Reflection\MethodReflection;
/**
* Method decorator for lazy loading value holder objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class LazyLoadingMethodInterceptor extends MethodGenerator
{
/**
* @param \Zend\Code\Reflection\MethodReflection $originalMethod
* @param \Zend\Code\Generator\PropertyGenerator $initializerProperty
* @param \Zend\Code\Generator\MethodGenerator $callInitializer
*
* @return LazyLoadingMethodInterceptor|static
*/
public static function generateMethod(
MethodReflection $originalMethod,
PropertyGenerator $initializerProperty,
ZendMethodGenerator $callInitializer
) {
/* @var $method self */
$method = static::fromReflection($originalMethod);
$parameters = $originalMethod->getParameters();
$methodName = $originalMethod->getName();
$initializerParams = array();
$forwardedParams = array();
foreach ($parameters as $parameter) {
$parameterName = $parameter->getName();
$initializerParams[] = var_export($parameterName, true) . ' => $' . $parameterName;
$forwardedParams[] = '$' . $parameterName;
}
$method->setBody(
'$this->' . $initializerProperty->getName()
. ' && $this->' . $callInitializer->getName()
. '(' . var_export($methodName, true)
. ', array(' . implode(', ', $initializerParams) . "));\n\n"
. 'return parent::'
. $methodName . '(' . implode(', ', $forwardedParams) . ');'
);
$method->setDocblock('{@inheritDoc}');
return $method;
}
}

View File

@@ -1,55 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManager\ProxyGenerator\NullObject\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ReflectionClass;
use ReflectionProperty;
/**
* The `__construct` implementation for null object proxies
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
class Constructor extends MethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass Reflection of the class to proxy
*/
public function __construct(ReflectionClass $originalClass)
{
parent::__construct('__construct');
/* @var $publicProperties \ReflectionProperty[] */
$publicProperties = $originalClass->getProperties(ReflectionProperty::IS_PUBLIC);
$nullableProperties = array();
foreach ($publicProperties as $publicProperty) {
$nullableProperties[] = '$this->' . $publicProperty->getName() . ' = null;';
}
$this->setDocblock("@override constructor for null object initialization");
if ($nullableProperties) {
$this->setBody(implode("\n", $nullableProperties));
}
}
}

View File

@@ -1,58 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManager\ProxyGenerator\PropertyGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use ReflectionClass;
use ReflectionProperty;
use Zend\Code\Generator\PropertyGenerator;
/**
* Map of public properties that exist in the class being proxied
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class PublicPropertiesDefaults extends PropertyGenerator
{
/**
* @var bool[]
*/
private $publicProperties = array();
/**
* @param \ReflectionClass $originalClass
*/
public function __construct(ReflectionClass $originalClass)
{
parent::__construct(UniqueIdentifierGenerator::getIdentifier('publicPropertiesDefaults'));
$defaults = $originalClass->getDefaultProperties();
foreach ($originalClass->getProperties(ReflectionProperty::IS_PUBLIC) as $publicProperty) {
$name = $publicProperty->getName();
$this->publicProperties[$name] = $defaults[$name];
}
$this->setDefaultValue($this->publicProperties);
$this->setVisibility(self::VISIBILITY_PRIVATE);
$this->setStatic(true);
$this->setDocblock('@var mixed[] map of default property values of the parent class');
}
}

View File

@@ -1,63 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManager\ProxyGenerator\RemoteObject\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\Generator\ParameterGenerator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* The `__construct` implementation for remote object proxies
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
class Constructor extends MethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass Reflection of the class to proxy
* @param PropertyGenerator $adapter Adapter property
*/
public function __construct(ReflectionClass $originalClass, PropertyGenerator $adapter)
{
parent::__construct('__construct');
$adapterName = $adapter->getName();
$this->setParameter(new ParameterGenerator($adapterName, 'ProxyManager\Factory\RemoteObject\AdapterInterface'));
$this->setDocblock(
'@override constructor for remote object control\n\n'
. '@param \\ProxyManager\\Factory\\RemoteObject\\AdapterInterface \$adapter'
);
$body = '$this->' . $adapterName . ' = $' . $adapterName . ';';
foreach ($originalClass->getProperties() as $property) {
if ($property->isPublic() && ! $property->isStatic()) {
$body .= "\nunset(\$this->" . $property->getName() . ');';
}
}
$this->setBody($body);
}
}

View File

@@ -1,133 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Autoloader;
use PHPUnit_Framework_TestCase;
use ProxyManager\Autoloader\Autoloader;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
/**
* Tests for {@see \ProxyManager\Autoloader\Autoloader}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\Autoloader\Autoloader
* @group Coverage
*/
class AutoloaderTest extends PHPUnit_Framework_TestCase
{
/**
* @var \ProxyManager\Autoloader\Autoloader
*/
protected $autoloader;
/**
* @var \ProxyManager\FileLocator\FileLocatorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $fileLocator;
/**
* @var \ProxyManager\Inflector\ClassNameInflectorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $classNameInflector;
/**
* @covers \ProxyManager\Autoloader\Autoloader::__construct
*/
public function setUp()
{
$this->fileLocator = $this->getMock('ProxyManager\\FileLocator\\FileLocatorInterface');
$this->classNameInflector = $this->getMock('ProxyManager\\Inflector\\ClassNameInflectorInterface');
$this->autoloader = new Autoloader($this->fileLocator, $this->classNameInflector);
}
/**
* @covers \ProxyManager\Autoloader\Autoloader::__invoke
*/
public function testWillNotAutoloadUserClasses()
{
$className = 'Foo\\' . UniqueIdentifierGenerator::getIdentifier('Bar');
$this
->classNameInflector
->expects($this->once())
->method('isProxyClassName')
->with($className)
->will($this->returnValue(false));
$this->assertFalse($this->autoloader->__invoke($className));
}
/**
* @covers \ProxyManager\Autoloader\Autoloader::__invoke
*/
public function testWillNotAutoloadNonExistingClass()
{
$className = 'Foo\\' . UniqueIdentifierGenerator::getIdentifier('Bar');
$this
->classNameInflector
->expects($this->once())
->method('isProxyClassName')
->with($className)
->will($this->returnValue(true));
$this
->fileLocator
->expects($this->once())
->method('getProxyFileName')
->will($this->returnValue(__DIR__ . '/non-existing'));
$this->assertFalse($this->autoloader->__invoke($className));
}
/**
* @covers \ProxyManager\Autoloader\Autoloader::__invoke
*/
public function testWillNotAutoloadExistingClass()
{
$this->assertFalse($this->autoloader->__invoke(__CLASS__));
}
/**
* @covers \ProxyManager\Autoloader\Autoloader::__invoke
*/
public function testWillAutoloadExistingFile()
{
$namespace = 'Foo';
$className = UniqueIdentifierGenerator::getIdentifier('Bar');
$fqcn = $namespace . '\\' . $className;
$fileName = sys_get_temp_dir() . '/foo_' . uniqid() . '.php';
file_put_contents($fileName, '<?php namespace ' . $namespace . '; class ' . $className . '{}');
$this
->classNameInflector
->expects($this->once())
->method('isProxyClassName')
->with($fqcn)
->will($this->returnValue(true));
$this
->fileLocator
->expects($this->once())
->method('getProxyFileName')
->will($this->returnValue($fileName));
$this->assertTrue($this->autoloader->__invoke($fqcn));
$this->assertTrue(class_exists($fqcn, false));
}
}

View File

@@ -1,183 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest;
use PHPUnit_Framework_TestCase;
use ProxyManager\Configuration;
/**
* Tests for {@see \ProxyManager\Configuration}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class ConfigurationTest extends PHPUnit_Framework_TestCase
{
/**
* @var \ProxyManager\Configuration
*/
protected $configuration;
/**
* {@inheritDoc}
*/
public function setUp()
{
$this->configuration = new Configuration();
}
/**
* @covers \ProxyManager\Configuration::getProxiesNamespace
* @covers \ProxyManager\Configuration::setProxiesNamespace
*/
public function testGetSetProxiesNamespace()
{
$this->assertSame(
'ProxyManagerGeneratedProxy',
$this->configuration->getProxiesNamespace(),
'Default setting check for BC'
);
$this->configuration->setProxiesNamespace('foo');
$this->assertSame('foo', $this->configuration->getProxiesNamespace());
}
/**
* @covers \ProxyManager\Configuration::getClassNameInflector
* @covers \ProxyManager\Configuration::setClassNameInflector
*/
public function testSetGetClassNameInflector()
{
$this->assertInstanceOf(
'ProxyManager\\Inflector\\ClassNameInflectorInterface',
$this->configuration->getClassNameInflector()
);
/* @var $inflector \ProxyManager\Inflector\ClassNameInflectorInterface */
$inflector = $this->getMock('ProxyManager\\Inflector\\ClassNameInflectorInterface');
$this->configuration->setClassNameInflector($inflector);
$this->assertSame($inflector, $this->configuration->getClassNameInflector());
}
/**
* @covers \ProxyManager\Configuration::getGeneratorStrategy
* @covers \ProxyManager\Configuration::setGeneratorStrategy
*/
public function testSetGetGeneratorStrategy()
{
$this->assertInstanceOf(
'ProxyManager\\GeneratorStrategy\\GeneratorStrategyInterface',
$this->configuration->getGeneratorStrategy()
);
/* @var $strategy \ProxyManager\GeneratorStrategy\GeneratorStrategyInterface */
$strategy = $this->getMock('ProxyManager\\GeneratorStrategy\\GeneratorStrategyInterface');
$this->configuration->setGeneratorStrategy($strategy);
$this->assertSame($strategy, $this->configuration->getGeneratorStrategy());
}
/**
* @covers \ProxyManager\Configuration::getProxiesTargetDir
* @covers \ProxyManager\Configuration::setProxiesTargetDir
*/
public function testSetGetProxiesTargetDir()
{
$this->assertTrue(is_dir($this->configuration->getProxiesTargetDir()));
$this->configuration->setProxiesTargetDir(__DIR__);
$this->assertSame(__DIR__, $this->configuration->getProxiesTargetDir());
}
/**
* @covers \ProxyManager\Configuration::getProxyAutoloader
* @covers \ProxyManager\Configuration::setProxyAutoloader
*/
public function testSetGetProxyAutoloader()
{
$this->assertInstanceOf(
'ProxyManager\\Autoloader\\AutoloaderInterface',
$this->configuration->getProxyAutoloader()
);
/* @var $autoloader \ProxyManager\Autoloader\AutoloaderInterface */
$autoloader = $this->getMock('ProxyManager\\Autoloader\\AutoloaderInterface');
$this->configuration->setProxyAutoloader($autoloader);
$this->assertSame($autoloader, $this->configuration->getProxyAutoloader());
}
/**
* @covers \ProxyManager\Configuration::getSignatureGenerator
* @covers \ProxyManager\Configuration::setSignatureGenerator
*/
public function testSetGetSignatureGenerator()
{
$this->assertInstanceOf(
'ProxyManager\\Signature\\SignatureGeneratorInterface',
$this->configuration->getSignatureGenerator()
);
/* @var $signatureGenerator \ProxyManager\Signature\SignatureGeneratorInterface */
$signatureGenerator = $this->getMock('ProxyManager\\Signature\\SignatureGeneratorInterface');
$this->configuration->setSignatureGenerator($signatureGenerator);
$this->assertSame($signatureGenerator, $this->configuration->getSignatureGenerator());
}
/**
* @covers \ProxyManager\Configuration::getSignatureChecker
* @covers \ProxyManager\Configuration::setSignatureChecker
*/
public function testSetGetSignatureChecker()
{
$this->assertInstanceOf(
'ProxyManager\\Signature\\SignatureCheckerInterface',
$this->configuration->getSignatureChecker()
);
/* @var $signatureChecker \ProxyManager\Signature\SignatureCheckerInterface */
$signatureChecker = $this->getMock('ProxyManager\\Signature\\SignatureCheckerInterface');
$this->configuration->setSignatureChecker($signatureChecker);
$this->assertSame($signatureChecker, $this->configuration->getSignatureChecker());
}
/**
* @covers \ProxyManager\Configuration::getClassSignatureGenerator
* @covers \ProxyManager\Configuration::setClassSignatureGenerator
*/
public function testSetGetClassSignatureGenerator()
{
$this->assertInstanceOf(
'ProxyManager\\Signature\\ClassSignatureGeneratorInterface',
$this->configuration->getClassSignatureGenerator()
);
/* @var $classSignatureGenerator \ProxyManager\Signature\ClassSignatureGeneratorInterface */
$classSignatureGenerator = $this->getMock('ProxyManager\\Signature\\ClassSignatureGeneratorInterface');
$this->configuration->setClassSignatureGenerator($classSignatureGenerator);
$this->assertSame($classSignatureGenerator, $this->configuration->getClassSignatureGenerator());
}
}

View File

@@ -1,44 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Exception;
use PHPUnit_Framework_TestCase;
use ProxyManager\Exception\DisabledMethodException;
/**
* Tests for {@see \ProxyManager\Exception\DisabledMethodException}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\Exception\DisabledMethodException
* @group Coverage
*/
class DisabledMethodExceptionTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\Exception\DisabledMethodException::disabledMethod
*/
public function testProxyDirectoryNotFound()
{
$exception = DisabledMethodException::disabledMethod('foo::bar');
$this->assertSame('Method "foo::bar" is forcefully disabled', $exception->getMessage());
}
}

View File

@@ -1,72 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Exception;
use PHPUnit_Framework_TestCase;
use ProxyManager\Exception\FileNotWritableException;
/**
* Tests for {@see \ProxyManager\Exception\FileNotWritableException}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\Exception\FileNotWritableException
* @group Coverage
*/
class FileNotWritableExceptionTest extends PHPUnit_Framework_TestCase
{
public function testFromInvalidMoveOperation()
{
$exception = FileNotWritableException::fromInvalidMoveOperation('/tmp/a', '/tmp/b');
$this->assertInstanceOf('ProxyManager\\Exception\\FileNotWritableException', $exception);
$this->assertSame(
'Could not move file "/tmp/a" to location "/tmp/b": either the source file is not readable,'
. ' or the destination is not writable',
$exception->getMessage()
);
}
public function testFromNotWritableLocationWithNonFilePath()
{
$exception = FileNotWritableException::fromNonWritableLocation(__DIR__);
$this->assertInstanceOf('ProxyManager\\Exception\\FileNotWritableException', $exception);
$this->assertSame(
'Could not write to path "' . __DIR__ . '": exists and is not a file',
$exception->getMessage()
);
}
public function testFromNotWritableLocationWithNonWritablePath()
{
$path = sys_get_temp_dir() . '/' . uniqid('FileNotWritableExceptionTestNonWritable', true);
mkdir($path, 0555);
$exception = FileNotWritableException::fromNonWritableLocation($path . '/foo');
$this->assertInstanceOf('ProxyManager\\Exception\\FileNotWritableException', $exception);
$this->assertSame(
'Could not write to path "' . $path . '/foo": is not writable',
$exception->getMessage()
);
}
}

View File

@@ -1,67 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Exception;
use PHPUnit_Framework_TestCase;
use ProxyManager\Exception\InvalidProxiedClassException;
use ReflectionClass;
/**
* Tests for {@see \ProxyManager\Exception\InvalidProxiedClassException}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\Exception\InvalidProxiedClassException
* @group Coverage
*/
class InvalidProxiedClassExceptionTest extends PHPUnit_Framework_TestCase
{
public function testInterfaceNotSupported()
{
$this->assertSame(
'Provided interface "ProxyManagerTestAsset\BaseInterface" cannot be proxied',
InvalidProxiedClassException::interfaceNotSupported(
new ReflectionClass('ProxyManagerTestAsset\BaseInterface')
)->getMessage()
);
}
public function testFinalClassNotSupported()
{
$this->assertSame(
'Provided class "ProxyManagerTestAsset\FinalClass" is final and cannot be proxied',
InvalidProxiedClassException::finalClassNotSupported(
new ReflectionClass('ProxyManagerTestAsset\FinalClass')
)->getMessage()
);
}
public function testAbstractProtectedMethodsNotSupported()
{
$this->assertSame(
'Provided class "ProxyManagerTestAsset\ClassWithAbstractProtectedMethod" has following protected abstract'
. ' methods, and therefore cannot be proxied:' . "\n"
. 'ProxyManagerTestAsset\ClassWithAbstractProtectedMethod::protectedAbstractMethod',
InvalidProxiedClassException::abstractProtectedMethodsNotSupported(
new ReflectionClass('ProxyManagerTestAsset\ClassWithAbstractProtectedMethod')
)->getMessage()
);
}
}

View File

@@ -1,44 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Exception;
use PHPUnit_Framework_TestCase;
use ProxyManager\Exception\InvalidProxyDirectoryException;
/**
* Tests for {@see \ProxyManager\Exception\InvalidProxyDirectoryException}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\Exception\InvalidProxyDirectoryException
* @group Coverage
*/
class InvalidProxyDirectoryExceptionTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\Exception\InvalidProxyDirectoryException::proxyDirectoryNotFound
*/
public function testProxyDirectoryNotFound()
{
$exception = InvalidProxyDirectoryException::proxyDirectoryNotFound('foo/bar');
$this->assertSame('Provided directory "foo/bar" does not exist', $exception->getMessage());
}
}

View File

@@ -1,49 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Exception;
use PHPUnit_Framework_TestCase;
use ProxyManager\Exception\UnsupportedProxiedClassException;
use ReflectionProperty;
/**
* Tests for {@see \ProxyManager\Exception\UnsupportedProxiedClassException}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\Exception\UnsupportedProxiedClassException
* @group Coverage
*/
class UnsupportedProxiedClassExceptionTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\Exception\UnsupportedProxiedClassException::unsupportedLocalizedReflectionProperty
*/
public function testUnsupportedLocalizedReflectionProperty()
{
$this->assertSame(
'Provided reflection property "property0" of class "ProxyManagerTestAsset\ClassWithPrivateProperties" '
. 'is private and cannot be localized in PHP 5.3',
UnsupportedProxiedClassException::unsupportedLocalizedReflectionProperty(
new ReflectionProperty('ProxyManagerTestAsset\ClassWithPrivateProperties', 'property0')
)->getMessage()
);
}
}

View File

@@ -1,158 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory;
use PHPUnit_Framework_TestCase;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use ReflectionMethod;
/**
* Tests for {@see \ProxyManager\Factory\AbstractBaseFactory}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\Factory\AbstractBaseFactory
* @group Coverage
*/
class AbstractBaseFactoryTest extends PHPUnit_Framework_TestCase
{
/**
* @var \ProxyManager\Factory\AbstractBaseFactory
*/
private $factory;
/**
* @var \ProxyManager\ProxyGenerator\ProxyGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $generator;
/**
* @var \ProxyManager\Inflector\ClassNameInflectorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $classNameInflector;
/**
* @var \ProxyManager\GeneratorStrategy\GeneratorStrategyInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $generatorStrategy;
/**
* @var \ProxyManager\Autoloader\AutoloaderInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $proxyAutoloader;
/**
* @var \ProxyManager\Signature\SignatureCheckerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $signatureChecker;
/**
* @var \ProxyManager\Signature\ClassSignatureGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $classSignatureGenerator;
/**
* {@inheritDoc}
*/
public function setUp()
{
$configuration = $this->getMock('ProxyManager\\Configuration');
$this->generator = $this->getMock('ProxyManager\\ProxyGenerator\\ProxyGeneratorInterface');
$this->classNameInflector = $this->getMock('ProxyManager\\Inflector\\ClassNameInflectorInterface');
$this->generatorStrategy = $this->getMock('ProxyManager\\GeneratorStrategy\\GeneratorStrategyInterface');
$this->proxyAutoloader = $this->getMock('ProxyManager\\Autoloader\\AutoloaderInterface');
$this->signatureChecker = $this->getMock('ProxyManager\\Signature\\SignatureCheckerInterface');
$this->classSignatureGenerator = $this->getMock('ProxyManager\\Signature\\ClassSignatureGeneratorInterface');
$configuration
->expects($this->any())
->method('getClassNameInflector')
->will($this->returnValue($this->classNameInflector));
$configuration
->expects($this->any())
->method('getGeneratorStrategy')
->will($this->returnValue($this->generatorStrategy));
$configuration
->expects($this->any())
->method('getProxyAutoloader')
->will($this->returnValue($this->proxyAutoloader));
$configuration
->expects($this->any())
->method('getSignatureChecker')
->will($this->returnValue($this->signatureChecker));
$configuration
->expects($this->any())
->method('getClassSignatureGenerator')
->will($this->returnValue($this->classSignatureGenerator));
$this
->classNameInflector
->expects($this->any())
->method('getUserClassName')
->will($this->returnValue('stdClass'));
$this->factory = $this->getMockForAbstractClass(
'ProxyManager\\Factory\\AbstractBaseFactory',
array($configuration)
);
$this->factory->expects($this->any())->method('getGenerator')->will($this->returnValue($this->generator));
}
public function testGeneratesClass()
{
$generateProxy = new ReflectionMethod($this->factory, 'generateProxy');
$generateProxy->setAccessible(true);
$generatedClass = UniqueIdentifierGenerator::getIdentifier('fooBar');
$this
->classNameInflector
->expects($this->any())
->method('getProxyClassName')
->with('stdClass')
->will($this->returnValue($generatedClass));
$this
->generatorStrategy
->expects($this->once())
->method('generate')
->with($this->isInstanceOf('Zend\\Code\\Generator\\ClassGenerator'));
$this
->proxyAutoloader
->expects($this->once())
->method('__invoke')
->with($generatedClass)
->will($this->returnCallback(function ($className) {
eval('class ' . $className . ' {}');
}));
$this->signatureChecker->expects($this->atLeastOnce())->method('checkSignature');
$this->classSignatureGenerator->expects($this->once())->method('addSignature')->will($this->returnArgument(0));
$this->assertSame($generatedClass, $generateProxy->invoke($this->factory, 'stdClass'));
$this->assertTrue(class_exists($generatedClass, false));
$this->assertSame($generatedClass, $generateProxy->invoke($this->factory, 'stdClass'));
}
}

View File

@@ -1,199 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory;
use ProxyManager\Factory\AccessInterceptorValueHolderFactory;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use stdClass;
/**
* Tests for {@see \ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class AccessInterceptorScopeLocalizerFactoryTest extends PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $inflector;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $signatureChecker;
/**
* @var \ProxyManager\Signature\ClassSignatureGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $classSignatureGenerator;
/**
* @var \ProxyManager\Configuration|\PHPUnit_Framework_MockObject_MockObject
*/
protected $config;
/**
* {@inheritDoc}
*/
public function setUp()
{
$this->config = $this->getMock('ProxyManager\\Configuration');
$this->inflector = $this->getMock('ProxyManager\\Inflector\\ClassNameInflectorInterface');
$this->signatureChecker = $this->getMock('ProxyManager\\Signature\\SignatureCheckerInterface');
$this->classSignatureGenerator = $this->getMock('ProxyManager\\Signature\\ClassSignatureGeneratorInterface');
$this
->config
->expects($this->any())
->method('getClassNameInflector')
->will($this->returnValue($this->inflector));
$this
->config
->expects($this->any())
->method('getSignatureChecker')
->will($this->returnValue($this->signatureChecker));
$this
->config
->expects($this->any())
->method('getClassSignatureGenerator')
->will($this->returnValue($this->classSignatureGenerator));
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory::__construct
*/
public function testWithOptionalFactory()
{
$factory = new AccessInterceptorValueHolderFactory();
$this->assertAttributeNotEmpty('configuration', $factory);
$this->assertAttributeInstanceOf('ProxyManager\Configuration', 'configuration', $factory);
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory::__construct
* @covers \ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory::createProxy
* @covers \ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory::getGenerator
*/
public function testWillSkipAutoGeneration()
{
$instance = new stdClass();
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with('stdClass')
->will($this->returnValue('ProxyManagerTestAsset\\AccessInterceptorValueHolderMock'));
$factory = new AccessInterceptorScopeLocalizerFactory($this->config);
/* @var $proxy \ProxyManagerTestAsset\AccessInterceptorValueHolderMock */
$proxy = $factory->createProxy($instance, array('foo'), array('bar'));
$this->assertInstanceOf('ProxyManagerTestAsset\\AccessInterceptorValueHolderMock', $proxy);
$this->assertSame($instance, $proxy->instance);
$this->assertSame(array('foo'), $proxy->prefixInterceptors);
$this->assertSame(array('bar'), $proxy->suffixInterceptors);
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory::__construct
* @covers \ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory::createProxy
* @covers \ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory::getGenerator
*
* NOTE: serious mocking going on in here (a class is generated on-the-fly) - careful
*/
public function testWillTryAutoGeneration()
{
$instance = new stdClass();
$proxyClassName = UniqueIdentifierGenerator::getIdentifier('bar');
$generator = $this->getMock('ProxyManager\GeneratorStrategy\\GeneratorStrategyInterface');
$autoloader = $this->getMock('ProxyManager\\Autoloader\\AutoloaderInterface');
$this->config->expects($this->any())->method('getGeneratorStrategy')->will($this->returnValue($generator));
$this->config->expects($this->any())->method('getProxyAutoloader')->will($this->returnValue($autoloader));
$generator
->expects($this->once())
->method('generate')
->with(
$this->callback(
function (ClassGenerator $targetClass) use ($proxyClassName) {
return $targetClass->getName() === $proxyClassName;
}
)
);
// simulate autoloading
$autoloader
->expects($this->once())
->method('__invoke')
->with($proxyClassName)
->will(
$this->returnCallback(
function () use ($proxyClassName) {
eval(
'class ' . $proxyClassName
. ' extends \\ProxyManagerTestAsset\\AccessInterceptorValueHolderMock {}'
);
}
)
);
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with('stdClass')
->will($this->returnValue($proxyClassName));
$this
->inflector
->expects($this->once())
->method('getUserClassName')
->with('stdClass')
->will($this->returnValue('ProxyManagerTestAsset\\LazyLoadingMock'));
$this->signatureChecker->expects($this->atLeastOnce())->method('checkSignature');
$this->classSignatureGenerator->expects($this->once())->method('addSignature')->will($this->returnArgument(0));
$factory = new AccessInterceptorScopeLocalizerFactory($this->config);
/* @var $proxy \ProxyManagerTestAsset\AccessInterceptorValueHolderMock */
$proxy = $factory->createProxy($instance, array('foo'), array('bar'));
$this->assertInstanceOf($proxyClassName, $proxy);
$this->assertSame($instance, $proxy->instance);
$this->assertSame(array('foo'), $proxy->prefixInterceptors);
$this->assertSame(array('bar'), $proxy->suffixInterceptors);
}
}

View File

@@ -1,198 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\AccessInterceptorValueHolderFactory;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use stdClass;
/**
* Tests for {@see \ProxyManager\Factory\AccessInterceptorValueHolderFactory}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class AccessInterceptorValueHolderFactoryTest extends PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $inflector;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $signatureChecker;
/**
* @var \ProxyManager\Signature\ClassSignatureGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $classSignatureGenerator;
/**
* @var \ProxyManager\Configuration|\PHPUnit_Framework_MockObject_MockObject
*/
protected $config;
/**
* {@inheritDoc}
*/
public function setUp()
{
$this->config = $this->getMock('ProxyManager\\Configuration');
$this->inflector = $this->getMock('ProxyManager\\Inflector\\ClassNameInflectorInterface');
$this->signatureChecker = $this->getMock('ProxyManager\\Signature\\SignatureCheckerInterface');
$this->classSignatureGenerator = $this->getMock('ProxyManager\\Signature\\ClassSignatureGeneratorInterface');
$this
->config
->expects($this->any())
->method('getClassNameInflector')
->will($this->returnValue($this->inflector));
$this
->config
->expects($this->any())
->method('getSignatureChecker')
->will($this->returnValue($this->signatureChecker));
$this
->config
->expects($this->any())
->method('getClassSignatureGenerator')
->will($this->returnValue($this->classSignatureGenerator));
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\AccessInterceptorValueHolderFactory::__construct
*/
public function testWithOptionalFactory()
{
$factory = new AccessInterceptorValueHolderFactory();
$this->assertAttributeNotEmpty('configuration', $factory);
$this->assertAttributeInstanceOf('ProxyManager\Configuration', 'configuration', $factory);
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\AccessInterceptorValueHolderFactory::__construct
* @covers \ProxyManager\Factory\AccessInterceptorValueHolderFactory::createProxy
* @covers \ProxyManager\Factory\AccessInterceptorValueHolderFactory::getGenerator
*/
public function testWillSkipAutoGeneration()
{
$instance = new stdClass();
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with('stdClass')
->will($this->returnValue('ProxyManagerTestAsset\\AccessInterceptorValueHolderMock'));
$factory = new AccessInterceptorValueHolderFactory($this->config);
/* @var $proxy \ProxyManagerTestAsset\AccessInterceptorValueHolderMock */
$proxy = $factory->createProxy($instance, array('foo'), array('bar'));
$this->assertInstanceOf('ProxyManagerTestAsset\\AccessInterceptorValueHolderMock', $proxy);
$this->assertSame($instance, $proxy->instance);
$this->assertSame(array('foo'), $proxy->prefixInterceptors);
$this->assertSame(array('bar'), $proxy->suffixInterceptors);
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\AccessInterceptorValueHolderFactory::__construct
* @covers \ProxyManager\Factory\AccessInterceptorValueHolderFactory::createProxy
* @covers \ProxyManager\Factory\AccessInterceptorValueHolderFactory::getGenerator
*
* NOTE: serious mocking going on in here (a class is generated on-the-fly) - careful
*/
public function testWillTryAutoGeneration()
{
$instance = new stdClass();
$proxyClassName = UniqueIdentifierGenerator::getIdentifier('bar');
$generator = $this->getMock('ProxyManager\GeneratorStrategy\\GeneratorStrategyInterface');
$autoloader = $this->getMock('ProxyManager\\Autoloader\\AutoloaderInterface');
$this->config->expects($this->any())->method('getGeneratorStrategy')->will($this->returnValue($generator));
$this->config->expects($this->any())->method('getProxyAutoloader')->will($this->returnValue($autoloader));
$generator
->expects($this->once())
->method('generate')
->with(
$this->callback(
function (ClassGenerator $targetClass) use ($proxyClassName) {
return $targetClass->getName() === $proxyClassName;
}
)
);
// simulate autoloading
$autoloader
->expects($this->once())
->method('__invoke')
->with($proxyClassName)
->will(
$this->returnCallback(
function () use ($proxyClassName) {
eval(
'class ' . $proxyClassName
. ' extends \\ProxyManagerTestAsset\\AccessInterceptorValueHolderMock {}'
);
}
)
);
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with('stdClass')
->will($this->returnValue($proxyClassName));
$this
->inflector
->expects($this->once())
->method('getUserClassName')
->with('stdClass')
->will($this->returnValue('ProxyManagerTestAsset\\LazyLoadingMock'));
$this->signatureChecker->expects($this->atLeastOnce())->method('checkSignature');
$this->classSignatureGenerator->expects($this->once())->method('addSignature')->will($this->returnArgument(0));
$factory = new AccessInterceptorValueHolderFactory($this->config);
/* @var $proxy \ProxyManagerTestAsset\AccessInterceptorValueHolderMock */
$proxy = $factory->createProxy($instance, array('foo'), array('bar'));
$this->assertInstanceOf($proxyClassName, $proxy);
$this->assertSame($instance, $proxy->instance);
$this->assertSame(array('foo'), $proxy->prefixInterceptors);
$this->assertSame(array('bar'), $proxy->suffixInterceptors);
}
}

View File

@@ -1,193 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\LazyLoadingGhostFactory;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
/**
* Tests for {@see \ProxyManager\Factory\LazyLoadingGhostFactory}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class LazyLoadingGhostFactoryTest extends PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $inflector;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $signatureChecker;
/**
* @var \ProxyManager\Signature\ClassSignatureGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $classSignatureGenerator;
/**
* @var \ProxyManager\Configuration|\PHPUnit_Framework_MockObject_MockObject
*/
protected $config;
/**
* {@inheritDoc}
*/
public function setUp()
{
$this->config = $this->getMock('ProxyManager\\Configuration');
$this->inflector = $this->getMock('ProxyManager\\Inflector\\ClassNameInflectorInterface');
$this->signatureChecker = $this->getMock('ProxyManager\\Signature\\SignatureCheckerInterface');
$this->classSignatureGenerator = $this->getMock('ProxyManager\\Signature\\ClassSignatureGeneratorInterface');
$this
->config
->expects($this->any())
->method('getClassNameInflector')
->will($this->returnValue($this->inflector));
$this
->config
->expects($this->any())
->method('getSignatureChecker')
->will($this->returnValue($this->signatureChecker));
$this
->config
->expects($this->any())
->method('getClassSignatureGenerator')
->will($this->returnValue($this->classSignatureGenerator));
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\LazyLoadingGhostFactory::__construct
*/
public function testWithOptionalFactory()
{
$factory = new LazyLoadingGhostFactory();
$this->assertAttributeNotEmpty('configuration', $factory);
$this->assertAttributeInstanceOf('ProxyManager\Configuration', 'configuration', $factory);
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\LazyLoadingGhostFactory::__construct
* @covers \ProxyManager\Factory\LazyLoadingGhostFactory::createProxy
*/
public function testWillSkipAutoGeneration()
{
$className = UniqueIdentifierGenerator::getIdentifier('foo');
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with($className)
->will($this->returnValue('ProxyManagerTestAsset\\LazyLoadingMock'));
$factory = new LazyLoadingGhostFactory($this->config);
$initializer = function () {
};
/* @var $proxy \ProxyManagerTestAsset\LazyLoadingMock */
$proxy = $factory->createProxy($className, $initializer);
$this->assertInstanceOf('ProxyManagerTestAsset\\LazyLoadingMock', $proxy);
$this->assertSame($initializer, $proxy->initializer);
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\LazyLoadingGhostFactory::__construct
* @covers \ProxyManager\Factory\LazyLoadingGhostFactory::createProxy
* @covers \ProxyManager\Factory\LazyLoadingGhostFactory::getGenerator
*
* NOTE: serious mocking going on in here (a class is generated on-the-fly) - careful
*/
public function testWillTryAutoGeneration()
{
$className = UniqueIdentifierGenerator::getIdentifier('foo');
$proxyClassName = UniqueIdentifierGenerator::getIdentifier('bar');
$generator = $this->getMock('ProxyManager\\GeneratorStrategy\\GeneratorStrategyInterface');
$autoloader = $this->getMock('ProxyManager\\Autoloader\\AutoloaderInterface');
$this->config->expects($this->any())->method('getGeneratorStrategy')->will($this->returnValue($generator));
$this->config->expects($this->any())->method('getProxyAutoloader')->will($this->returnValue($autoloader));
$generator
->expects($this->once())
->method('generate')
->with(
$this->callback(
function (ClassGenerator $targetClass) use ($proxyClassName) {
return $targetClass->getName() === $proxyClassName;
}
)
);
// simulate autoloading
$autoloader
->expects($this->once())
->method('__invoke')
->with($proxyClassName)
->will(
$this->returnCallback(
function () use ($proxyClassName) {
eval('class ' . $proxyClassName . ' extends \\ProxyManagerTestAsset\\LazyLoadingMock {}');
}
)
);
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with($className)
->will($this->returnValue($proxyClassName));
$this
->inflector
->expects($this->once())
->method('getUserClassName')
->with($className)
->will($this->returnValue('ProxyManagerTestAsset\\LazyLoadingMock'));
$this->signatureChecker->expects($this->atLeastOnce())->method('checkSignature');
$this->classSignatureGenerator->expects($this->once())->method('addSignature')->will($this->returnArgument(0));
$factory = new LazyLoadingGhostFactory($this->config);
$initializer = function () {
};
/* @var $proxy \ProxyManagerTestAsset\LazyLoadingMock */
$proxy = $factory->createProxy($className, $initializer);
$this->assertInstanceOf($proxyClassName, $proxy);
$this->assertSame($initializer, $proxy->initializer);
}
}

View File

@@ -1,193 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
/**
* Tests for {@see \ProxyManager\Factory\LazyLoadingValueHolderFactory}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class LazyLoadingValueHolderFactoryTest extends PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $inflector;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $signatureChecker;
/**
* @var \ProxyManager\Signature\ClassSignatureGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $classSignatureGenerator;
/**
* @var \ProxyManager\Configuration|\PHPUnit_Framework_MockObject_MockObject
*/
protected $config;
/**
* {@inheritDoc}
*/
public function setUp()
{
$this->config = $this->getMock('ProxyManager\\Configuration');
$this->inflector = $this->getMock('ProxyManager\\Inflector\\ClassNameInflectorInterface');
$this->signatureChecker = $this->getMock('ProxyManager\\Signature\\SignatureCheckerInterface');
$this->classSignatureGenerator = $this->getMock('ProxyManager\\Signature\\ClassSignatureGeneratorInterface');
$this
->config
->expects($this->any())
->method('getClassNameInflector')
->will($this->returnValue($this->inflector));
$this
->config
->expects($this->any())
->method('getSignatureChecker')
->will($this->returnValue($this->signatureChecker));
$this
->config
->expects($this->any())
->method('getClassSignatureGenerator')
->will($this->returnValue($this->classSignatureGenerator));
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\LazyLoadingValueHolderFactory::__construct
*/
public function testWithOptionalFactory()
{
$factory = new LazyLoadingValueHolderFactory();
$this->assertAttributeNotEmpty('configuration', $factory);
$this->assertAttributeInstanceOf('ProxyManager\Configuration', 'configuration', $factory);
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\LazyLoadingValueHolderFactory::__construct
* @covers \ProxyManager\Factory\LazyLoadingValueHolderFactory::createProxy
*/
public function testWillSkipAutoGeneration()
{
$className = UniqueIdentifierGenerator::getIdentifier('foo');
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with($className)
->will($this->returnValue('ProxyManagerTestAsset\\LazyLoadingMock'));
$factory = new LazyLoadingValueHolderFactory($this->config);
$initializer = function () {
};
/* @var $proxy \ProxyManagerTestAsset\LazyLoadingMock */
$proxy = $factory->createProxy($className, $initializer);
$this->assertInstanceOf('ProxyManagerTestAsset\\LazyLoadingMock', $proxy);
$this->assertSame($initializer, $proxy->initializer);
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\LazyLoadingValueHolderFactory::__construct
* @covers \ProxyManager\Factory\LazyLoadingValueHolderFactory::createProxy
* @covers \ProxyManager\Factory\LazyLoadingValueHolderFactory::getGenerator
*
* NOTE: serious mocking going on in here (a class is generated on-the-fly) - careful
*/
public function testWillTryAutoGeneration()
{
$className = UniqueIdentifierGenerator::getIdentifier('foo');
$proxyClassName = UniqueIdentifierGenerator::getIdentifier('bar');
$generator = $this->getMock('ProxyManager\\GeneratorStrategy\\GeneratorStrategyInterface');
$autoloader = $this->getMock('ProxyManager\\Autoloader\\AutoloaderInterface');
$this->config->expects($this->any())->method('getGeneratorStrategy')->will($this->returnValue($generator));
$this->config->expects($this->any())->method('getProxyAutoloader')->will($this->returnValue($autoloader));
$generator
->expects($this->once())
->method('generate')
->with(
$this->callback(
function (ClassGenerator $targetClass) use ($proxyClassName) {
return $targetClass->getName() === $proxyClassName;
}
)
);
// simulate autoloading
$autoloader
->expects($this->once())
->method('__invoke')
->with($proxyClassName)
->will(
$this->returnCallback(
function () use ($proxyClassName) {
eval('class ' . $proxyClassName . ' extends \\ProxyManagerTestAsset\\LazyLoadingMock {}');
}
)
);
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with($className)
->will($this->returnValue($proxyClassName));
$this
->inflector
->expects($this->once())
->method('getUserClassName')
->with($className)
->will($this->returnValue('ProxyManagerTestAsset\\LazyLoadingMock'));
$this->signatureChecker->expects($this->atLeastOnce())->method('checkSignature');
$this->classSignatureGenerator->expects($this->once())->method('addSignature')->will($this->returnArgument(0));
$factory = new LazyLoadingValueHolderFactory($this->config);
$initializer = function () {
};
/* @var $proxy \ProxyManagerTestAsset\LazyLoadingMock */
$proxy = $factory->createProxy($className, $initializer);
$this->assertInstanceOf($proxyClassName, $proxy);
$this->assertSame($initializer, $proxy->initializer);
}
}

View File

@@ -1,180 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\NullObjectFactory;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use stdClass;
/**
* Tests for {@see \ProxyManager\Factory\NullObjectFactory}
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*
* @group Coverage
*/
class NullObjectFactoryTest extends PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $inflector;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $signatureChecker;
/**
* @var \ProxyManager\Signature\ClassSignatureGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $classSignatureGenerator;
/**
* @var \ProxyManager\Configuration|\PHPUnit_Framework_MockObject_MockObject
*/
protected $config;
/**
* {@inheritDoc}
*/
public function setUp()
{
$this->config = $this->getMock('ProxyManager\\Configuration');
$this->inflector = $this->getMock('ProxyManager\\Inflector\\ClassNameInflectorInterface');
$this->signatureChecker = $this->getMock('ProxyManager\\Signature\\SignatureCheckerInterface');
$this->classSignatureGenerator = $this->getMock('ProxyManager\\Signature\\ClassSignatureGeneratorInterface');
$this
->config
->expects($this->any())
->method('getClassNameInflector')
->will($this->returnValue($this->inflector));
$this
->config
->expects($this->any())
->method('getSignatureChecker')
->will($this->returnValue($this->signatureChecker));
$this
->config
->expects($this->any())
->method('getClassSignatureGenerator')
->will($this->returnValue($this->classSignatureGenerator));
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\NullObjectFactory::__construct
* @covers \ProxyManager\Factory\NullObjectFactory::createProxy
* @covers \ProxyManager\Factory\NullObjectFactory::getGenerator
*/
public function testWillSkipAutoGeneration()
{
$instance = new stdClass();
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with('stdClass')
->will($this->returnValue('ProxyManagerTestAsset\\NullObjectMock'));
$factory = new NullObjectFactory($this->config);
/* @var $proxy \ProxyManagerTestAsset\NullObjectMock */
$proxy = $factory->createProxy($instance);
$this->assertInstanceOf('ProxyManagerTestAsset\\NullObjectMock', $proxy);
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\NullObjectFactory::__construct
* @covers \ProxyManager\Factory\NullObjectFactory::createProxy
* @covers \ProxyManager\Factory\NullObjectFactory::getGenerator
*
* NOTE: serious mocking going on in here (a class is generated on-the-fly) - careful
*/
public function testWillTryAutoGeneration()
{
$instance = new stdClass();
$proxyClassName = UniqueIdentifierGenerator::getIdentifier('bar');
$generator = $this->getMock('ProxyManager\GeneratorStrategy\\GeneratorStrategyInterface');
$autoloader = $this->getMock('ProxyManager\\Autoloader\\AutoloaderInterface');
$this->config->expects($this->any())->method('getGeneratorStrategy')->will($this->returnValue($generator));
$this->config->expects($this->any())->method('getProxyAutoloader')->will($this->returnValue($autoloader));
$generator
->expects($this->once())
->method('generate')
->with(
$this->callback(
function (ClassGenerator $targetClass) use ($proxyClassName) {
return $targetClass->getName() === $proxyClassName;
}
)
);
// simulate autoloading
$autoloader
->expects($this->once())
->method('__invoke')
->with($proxyClassName)
->will(
$this->returnCallback(
function () use ($proxyClassName) {
eval(
'class ' . $proxyClassName
. ' extends \\ProxyManagerTestAsset\\NullObjectMock {}'
);
}
)
);
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with('stdClass')
->will($this->returnValue($proxyClassName));
$this
->inflector
->expects($this->once())
->method('getUserClassName')
->with('stdClass')
->will($this->returnValue('ProxyManagerTestAsset\\NullObjectMock'));
$this->signatureChecker->expects($this->atLeastOnce())->method('checkSignature');
$this->classSignatureGenerator->expects($this->once())->method('addSignature')->will($this->returnArgument(0));
$factory = new NullObjectFactory($this->config);
/* @var $proxy \ProxyManagerTestAsset\NullObjectMock */
$proxy = $factory->createProxy($instance);
$this->assertInstanceOf($proxyClassName, $proxy);
}
}

View File

@@ -1,101 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory\RemoteObject\Adapter;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\RemoteObject\Adapter\Soap;
/**
* Tests for {@see \ProxyManager\Factory\RemoteObject\Adapter\Soap}
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*
* @group Coverage
*/
class BaseAdapterTest extends PHPUnit_Framework_TestCase
{
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\RemoteObject\Adapter\BaseAdapter::__construct
* @covers \ProxyManager\Factory\RemoteObject\Adapter\BaseAdapter::call
* @covers \ProxyManager\Factory\RemoteObject\Adapter\Soap::getServiceName
*/
public function testBaseAdapter()
{
$client = $this
->getMockBuilder('Zend\Server\Client')
->setMethods(array('call'))
->getMock();
$adapter = $this->getMockForAbstractClass(
'ProxyManager\\Factory\\RemoteObject\\Adapter\\BaseAdapter',
array($client)
);
$client
->expects($this->once())
->method('call')
->with('foobarbaz', array('tab' => 'taz'))
->will($this->returnValue('baz'));
$adapter
->expects($this->once())
->method('getServiceName')
->with('foo', 'bar')
->will($this->returnValue('foobarbaz'));
$this->assertSame('baz', $adapter->call('foo', 'bar', array('tab' => 'taz')));
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\RemoteObject\Adapter\BaseAdapter::__construct
* @covers \ProxyManager\Factory\RemoteObject\Adapter\BaseAdapter::call
* @covers \ProxyManager\Factory\RemoteObject\Adapter\Soap::getServiceName
*/
public function testBaseAdapterWithServiceMap()
{
$client = $this
->getMockBuilder('Zend\Server\Client')
->setMethods(array('call'))
->getMock();
$adapter = $this->getMockForAbstractClass(
'ProxyManager\\Factory\\RemoteObject\\Adapter\\BaseAdapter',
array($client, array('foobarbaz' => 'mapped'))
);
$client
->expects($this->once())
->method('call')
->with('mapped', array('tab' => 'taz'))
->will($this->returnValue('baz'));
$adapter
->expects($this->once())
->method('getServiceName')
->with('foo', 'bar')
->will($this->returnValue('foobarbaz'));
$this->assertSame('baz', $adapter->call('foo', 'bar', array('tab' => 'taz')));
}
}

View File

@@ -1,57 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory\RemoteObject\Adapter;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\RemoteObject\Adapter\JsonRpc;
/**
* Tests for {@see \ProxyManager\Factory\RemoteObject\Adapter\JsonRpc}
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*
* @group Coverage
*/
class JsonRpcTest extends PHPUnit_Framework_TestCase
{
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\RemoteObject\Adapter\JsonRpc::__construct
* @covers \ProxyManager\Factory\RemoteObject\Adapter\JsonRpc::getServiceName
*/
public function testCanBuildAdapterWithJsonRpcClient()
{
$client = $this
->getMockBuilder('Zend\Server\Client')
->setMethods(array('call'))
->getMock();
$adapter = new JsonRpc($client);
$client
->expects($this->once())
->method('call')
->with('foo.bar', array('tab' => 'taz'))
->will($this->returnValue('baz'));
$this->assertSame('baz', $adapter->call('foo', 'bar', array('tab' => 'taz')));
}
}

View File

@@ -1,57 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory\RemoteObject\Adapter;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\RemoteObject\Adapter\Soap;
/**
* Tests for {@see \ProxyManager\Factory\RemoteObject\Adapter\Soap}
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*
* @group Coverage
*/
class SoapTest extends PHPUnit_Framework_TestCase
{
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\RemoteObject\Adapter\Soap::__construct
* @covers \ProxyManager\Factory\RemoteObject\Adapter\Soap::getServiceName
*/
public function testCanBuildAdapterWithSoapRpcClient()
{
$client = $this
->getMockBuilder('Zend\Server\Client')
->setMethods(array('call'))
->getMock();
$adapter = new Soap($client);
$client
->expects($this->once())
->method('call')
->with('bar', array('tab' => 'taz'))
->will($this->returnValue('baz'));
$this->assertSame('baz', $adapter->call('foo', 'bar', array('tab' => 'taz')));
}
}

View File

@@ -1,57 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory\RemoteObject\Adapter;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\RemoteObject\Adapter\XmlRpc;
/**
* Tests for {@see \ProxyManager\Factory\RemoteObject\Adapter\XmlRpc}
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*
* @group Coverage
*/
class XmlRpcTest extends PHPUnit_Framework_TestCase
{
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\RemoteObject\Adapter\XmlRpc::__construct
* @covers \ProxyManager\Factory\RemoteObject\Adapter\XmlRpc::getServiceName
*/
public function testCanBuildAdapterWithXmlRpcClient()
{
$client = $this
->getMockBuilder('Zend\Server\Client')
->setMethods(array('call'))
->getMock();
$adapter = new XmlRpc($client);
$client
->expects($this->once())
->method('call')
->with('foo.bar', array('tab' => 'taz'))
->will($this->returnValue('baz'));
$this->assertSame('baz', $adapter->call('foo', 'bar', array('tab' => 'taz')));
}
}

View File

@@ -1,178 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Factory;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\RemoteObjectFactory;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
/**
* Tests for {@see \ProxyManager\Factory\RemoteObjectFactory}
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*
* @group Coverage
*/
class RemoteObjectFactoryTest extends PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $inflector;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $signatureChecker;
/**
* @var \ProxyManager\Signature\ClassSignatureGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $classSignatureGenerator;
/**
* @var \ProxyManager\Configuration|\PHPUnit_Framework_MockObject_MockObject
*/
protected $config;
/**
* {@inheritDoc}
*/
public function setUp()
{
$this->config = $this->getMock('ProxyManager\\Configuration');
$this->inflector = $this->getMock('ProxyManager\\Inflector\\ClassNameInflectorInterface');
$this->signatureChecker = $this->getMock('ProxyManager\\Signature\\SignatureCheckerInterface');
$this->classSignatureGenerator = $this->getMock('ProxyManager\\Signature\\ClassSignatureGeneratorInterface');
$this
->config
->expects($this->any())
->method('getClassNameInflector')
->will($this->returnValue($this->inflector));
$this
->config
->expects($this->any())
->method('getSignatureChecker')
->will($this->returnValue($this->signatureChecker));
$this
->config
->expects($this->any())
->method('getClassSignatureGenerator')
->will($this->returnValue($this->classSignatureGenerator));
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\RemoteObjectFactory::__construct
* @covers \ProxyManager\Factory\RemoteObjectFactory::createProxy
* @covers \ProxyManager\Factory\RemoteObjectFactory::getGenerator
*/
public function testWillSkipAutoGeneration()
{
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with('ProxyManagerTestAsset\\BaseInterface')
->will($this->returnValue('StdClass'));
$adapter = $this->getMock('ProxyManager\Factory\RemoteObject\AdapterInterface');
$factory = new RemoteObjectFactory($adapter, $this->config);
/* @var $proxy \stdClass */
$proxy = $factory->createProxy('ProxyManagerTestAsset\\BaseInterface', $adapter);
$this->assertInstanceOf('stdClass', $proxy);
}
/**
* {@inheritDoc}
*
* @covers \ProxyManager\Factory\RemoteObjectFactory::__construct
* @covers \ProxyManager\Factory\RemoteObjectFactory::createProxy
* @covers \ProxyManager\Factory\RemoteObjectFactory::getGenerator
*
* NOTE: serious mocking going on in here (a class is generated on-the-fly) - careful
*/
public function testWillTryAutoGeneration()
{
$proxyClassName = UniqueIdentifierGenerator::getIdentifier('bar');
$generator = $this->getMock('ProxyManager\GeneratorStrategy\\GeneratorStrategyInterface');
$autoloader = $this->getMock('ProxyManager\\Autoloader\\AutoloaderInterface');
$this->config->expects($this->any())->method('getGeneratorStrategy')->will($this->returnValue($generator));
$this->config->expects($this->any())->method('getProxyAutoloader')->will($this->returnValue($autoloader));
$generator
->expects($this->once())
->method('generate')
->with(
$this->callback(
function (ClassGenerator $targetClass) use ($proxyClassName) {
return $targetClass->getName() === $proxyClassName;
}
)
);
// simulate autoloading
$autoloader
->expects($this->once())
->method('__invoke')
->with($proxyClassName)
->will(
$this->returnCallback(
function () use ($proxyClassName) {
eval(
'class ' . $proxyClassName
. ' extends stdClass {}'
);
}
)
);
$this
->inflector
->expects($this->once())
->method('getProxyClassName')
->with('ProxyManagerTestAsset\\BaseInterface')
->will($this->returnValue($proxyClassName));
$this
->inflector
->expects($this->once())
->method('getUserClassName')
->with('ProxyManagerTestAsset\\BaseInterface')
->will($this->returnValue('stdClass'));
$this->signatureChecker->expects($this->atLeastOnce())->method('checkSignature');
$this->classSignatureGenerator->expects($this->once())->method('addSignature')->will($this->returnArgument(0));
$adapter = $this->getMock('ProxyManager\Factory\RemoteObject\AdapterInterface');
$factory = new RemoteObjectFactory($adapter, $this->config);
/* @var $proxy \stdClass */
$proxy = $factory->createProxy('ProxyManagerTestAsset\\BaseInterface', $adapter);
$this->assertInstanceOf($proxyClassName, $proxy);
}
}

View File

@@ -1,54 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\FileLocator;
use PHPUnit_Framework_TestCase;
use ProxyManager\FileLocator\FileLocator;
/**
* Tests for {@see \ProxyManager\FileLocator\FileLocator}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class FileLocatorTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\FileLocator\FileLocator::__construct
* @covers \ProxyManager\FileLocator\FileLocator::getProxyFileName
*/
public function testGetProxyFileName()
{
$locator = new FileLocator(__DIR__);
$this->assertSame(__DIR__ . DIRECTORY_SEPARATOR . 'FooBarBaz.php', $locator->getProxyFileName('Foo\\Bar\\Baz'));
$this->assertSame(__DIR__ . DIRECTORY_SEPARATOR . 'Foo_Bar_Baz.php', $locator->getProxyFileName('Foo_Bar_Baz'));
}
/**
* @covers \ProxyManager\FileLocator\FileLocator::__construct
*/
public function testRejectsNonExistingDirectory()
{
$this->setExpectedException('ProxyManager\\Exception\\InvalidProxyDirectoryException');
new FileLocator(__DIR__ . '/non-existing');
}
}

View File

@@ -1,388 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use PHPUnit_Framework_SkippedTestError;
use PHPUnit_Framework_TestCase;
use ProxyManager\Exception\UnsupportedProxiedClassException;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\Proxy\AccessInterceptorInterface;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizerGenerator;
use ProxyManagerTestAsset\BaseClass;
use ProxyManagerTestAsset\ClassWithPublicArrayProperty;
use ProxyManagerTestAsset\ClassWithPublicProperties;
use ProxyManagerTestAsset\ClassWithSelfHint;
use ReflectionClass;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizerGenerator} produced objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Functional
* @coversNothing
*/
class AccessInterceptorScopeLocalizerFunctionalTest extends PHPUnit_Framework_TestCase
{
/**
* {@inheritDoc}
*/
public static function setUpBeforeClass()
{
if (! method_exists('Closure', 'bind')) {
throw new PHPUnit_Framework_SkippedTestError(
'PHP 5.3 doesn\'t support scope localization of private properties'
);
}
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCalls($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface */
$proxy = new $proxyName($instance);
$this->assertProxySynchronized($instance, $proxy);
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$listener = $this->getMock('stdClass', array('__invoke'));
$listener
->expects($this->once())
->method('__invoke')
->with($proxy, $proxy, $method, $params, false);
$proxy->setMethodPrefixInterceptor(
$method,
function ($proxy, $instance, $method, $params, & $returnEarly) use ($listener) {
$listener->__invoke($proxy, $instance, $method, $params, $returnEarly);
}
);
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$random = uniqid();
$proxy->setMethodPrefixInterceptor(
$method,
function ($proxy, $instance, $method, $params, & $returnEarly) use ($random) {
$returnEarly = true;
return $random;
}
);
$this->assertSame($random, call_user_func_array(array($proxy, $method), $params));
$this->assertProxySynchronized($instance, $proxy);
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsWithSuffixListener($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface */
$proxy = new $proxyName($instance);
$listener = $this->getMock('stdClass', array('__invoke'));
$listener
->expects($this->once())
->method('__invoke')
->with($proxy, $proxy, $method, $params, $expectedValue, false);
$proxy->setMethodSuffixInterceptor(
$method,
function ($proxy, $instance, $method, $params, $returnValue, & $returnEarly) use ($listener) {
$listener->__invoke($proxy, $instance, $method, $params, $returnValue, $returnEarly);
}
);
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$random = uniqid();
$proxy->setMethodSuffixInterceptor(
$method,
function ($proxy, $instance, $method, $params, $returnValue, & $returnEarly) use ($random) {
$returnEarly = true;
return $random;
}
);
$this->assertSame($random, call_user_func_array(array($proxy, $method), $params));
$this->assertProxySynchronized($instance, $proxy);
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsAfterUnSerialization($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface */
$proxy = unserialize(serialize(new $proxyName($instance)));
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$this->assertProxySynchronized($instance, $proxy);
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsAfterCloning($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface */
$proxy = new $proxyName($instance);
$cloned = clone $proxy;
$this->assertProxySynchronized($instance, $proxy);
$this->assertSame($expectedValue, call_user_func_array(array($cloned, $method), $params));
$this->assertProxySynchronized($instance, $proxy);
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyReadAccess($instance, $proxy, $publicProperty, $propertyValue)
{
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface */
$this->assertSame($propertyValue, $proxy->$publicProperty);
$this->assertProxySynchronized($instance, $proxy);
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyWriteAccess($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface */
$newValue = uniqid();
$proxy->$publicProperty = $newValue;
$this->assertSame($newValue, $proxy->$publicProperty);
$this->assertProxySynchronized($instance, $proxy);
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyExistence($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface */
$this->assertSame(isset($instance->$publicProperty), isset($proxy->$publicProperty));
$this->assertProxySynchronized($instance, $proxy);
$instance->$publicProperty = null;
$this->assertFalse(isset($proxy->$publicProperty));
$this->assertProxySynchronized($instance, $proxy);
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyUnset($instance, $proxy, $publicProperty)
{
$this->markTestSkipped('It is currently not possible to synchronize properties un-setting');
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface */
unset($proxy->$publicProperty);
$this->assertFalse(isset($instance->$publicProperty));
$this->assertFalse(isset($proxy->$publicProperty));
$this->assertProxySynchronized($instance, $proxy);
}
/**
* Verifies that accessing a public property containing an array behaves like in a normal context
*/
public function testCanWriteToArrayKeysInPublicProperty()
{
$instance = new ClassWithPublicArrayProperty();
$className = get_class($instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicArrayProperty */
$proxy = new $proxyName($instance);
$proxy->arrayProperty['foo'] = 'bar';
$this->assertSame('bar', $proxy->arrayProperty['foo']);
$proxy->arrayProperty = array('tab' => 'taz');
$this->assertSame(array('tab' => 'taz'), $proxy->arrayProperty);
$this->assertProxySynchronized($instance, $proxy);
}
/**
* Verifies that public properties retrieved via `__get` don't get modified in the object state
*/
public function testWillNotModifyRetrievedPublicProperties()
{
$instance = new ClassWithPublicProperties();
$className = get_class($instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicProperties */
$proxy = new $proxyName($instance);
$variable = $proxy->property0;
$this->assertSame('property0', $variable);
$variable = 'foo';
$this->assertSame('property0', $proxy->property0);
$this->assertProxySynchronized($instance, $proxy);
}
/**
* Verifies that public properties references retrieved via `__get` modify in the object state
*/
public function testWillModifyByRefRetrievedPublicProperties()
{
$instance = new ClassWithPublicProperties();
$className = get_class($instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicProperties */
$proxy = new $proxyName($instance);
$variable = & $proxy->property0;
$this->assertSame('property0', $variable);
$variable = 'foo';
$this->assertSame('foo', $proxy->property0);
$this->assertProxySynchronized($instance, $proxy);
}
/**
* Generates a proxy for the given class name, and retrieves its class name
*
* @param string $parentClassName
*
* @return string
*
* @throws UnsupportedProxiedClassException
*/
private function generateProxy($parentClassName)
{
$generatedClassName = __NAMESPACE__ . '\\' . UniqueIdentifierGenerator::getIdentifier('Foo');
$generator = new AccessInterceptorScopeLocalizerGenerator();
$generatedClass = new ClassGenerator($generatedClassName);
$strategy = new EvaluatingGeneratorStrategy();
$generator->generate(new ReflectionClass($parentClassName), $generatedClass);
$strategy->generate($generatedClass);
return $generatedClassName;
}
/**
* Generates a list of object | invoked method | parameters | expected result
*
* @return array
*/
public function getProxyMethods()
{
$selfHintParam = new ClassWithSelfHint();
$data = array(
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicMethod',
array(),
'publicMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicTypeHintedMethod',
array('param' => new \stdClass()),
'publicTypeHintedMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicByReferenceMethod',
array(),
'publicByReferenceMethodDefault'
),
);
if (PHP_VERSION_ID >= 50401) {
// PHP < 5.4.1 misbehaves, throwing strict standards, see https://bugs.php.net/bug.php?id=60573
$data[] = array(
'ProxyManagerTestAsset\\ClassWithSelfHint',
new ClassWithSelfHint(),
'selfHintMethod',
array('parameter' => $selfHintParam),
$selfHintParam
);
}
return $data;
}
/**
* Generates proxies and instances with a public property to feed to the property accessor methods
*
* @return array
*/
public function getPropertyAccessProxies()
{
$instance1 = new BaseClass();
$proxyName1 = $this->generateProxy(get_class($instance1));
return array(
array(
$instance1,
new $proxyName1($instance1),
'publicProperty',
'publicPropertyDefault',
),
);
}
/**
* @param object $instance
* @param AccessInterceptorInterface $proxy
*/
private function assertProxySynchronized($instance, AccessInterceptorInterface $proxy)
{
$reflectionClass = new ReflectionClass($instance);
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$this->assertSame(
$property->getValue($instance),
$property->getValue($proxy),
'Property "' . $property->getName() . '" is synchronized between instance and proxy'
);
}
}
}

View File

@@ -1,360 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use PHPUnit_Framework_TestCase;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolderGenerator;
use ProxyManagerTestAsset\BaseClass;
use ProxyManagerTestAsset\ClassWithPublicArrayProperty;
use ProxyManagerTestAsset\ClassWithPublicProperties;
use ProxyManagerTestAsset\ClassWithSelfHint;
use ReflectionClass;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator} produced objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Functional
* @coversNothing
*/
class AccessInterceptorValueHolderFunctionalTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider getProxyMethods
*/
public function testMethodCalls($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface|\ProxyManager\Proxy\ValueHolderInterface */
$proxy = new $proxyName($instance);
$this->assertSame($instance, $proxy->getWrappedValueHolderValue());
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$listener = $this->getMock('stdClass', array('__invoke'));
$listener
->expects($this->once())
->method('__invoke')
->with($proxy, $instance, $method, $params, false);
$proxy->setMethodPrefixInterceptor(
$method,
function ($proxy, $instance, $method, $params, & $returnEarly) use ($listener) {
$listener->__invoke($proxy, $instance, $method, $params, $returnEarly);
}
);
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$random = uniqid();
$proxy->setMethodPrefixInterceptor(
$method,
function ($proxy, $instance, $method, $params, & $returnEarly) use ($random) {
$returnEarly = true;
return $random;
}
);
$this->assertSame($random, call_user_func_array(array($proxy, $method), $params));
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsWithSuffixListener($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface|\ProxyManager\Proxy\ValueHolderInterface */
$proxy = new $proxyName($instance);
$listener = $this->getMock('stdClass', array('__invoke'));
$listener
->expects($this->once())
->method('__invoke')
->with($proxy, $instance, $method, $params, $expectedValue, false);
$proxy->setMethodSuffixInterceptor(
$method,
function ($proxy, $instance, $method, $params, $returnValue, & $returnEarly) use ($listener) {
$listener->__invoke($proxy, $instance, $method, $params, $returnValue, $returnEarly);
}
);
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$random = uniqid();
$proxy->setMethodSuffixInterceptor(
$method,
function ($proxy, $instance, $method, $params, $returnValue, & $returnEarly) use ($random) {
$returnEarly = true;
return $random;
}
);
$this->assertSame($random, call_user_func_array(array($proxy, $method), $params));
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsAfterUnSerialization($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface|\ProxyManager\Proxy\ValueHolderInterface */
$proxy = unserialize(serialize(new $proxyName($instance)));
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$this->assertEquals($instance, $proxy->getWrappedValueHolderValue());
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsAfterCloning($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface|\ProxyManager\Proxy\ValueHolderInterface */
$proxy = new $proxyName($instance);
$cloned = clone $proxy;
$this->assertNotSame($proxy->getWrappedValueHolderValue(), $cloned->getWrappedValueHolderValue());
$this->assertSame($expectedValue, call_user_func_array(array($cloned, $method), $params));
$this->assertEquals($instance, $cloned->getWrappedValueHolderValue());
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyReadAccess($instance, $proxy, $publicProperty, $propertyValue)
{
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface|\ProxyManager\Proxy\ValueHolderInterface */
$this->assertSame($propertyValue, $proxy->$publicProperty);
$this->assertEquals($instance, $proxy->getWrappedValueHolderValue());
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyWriteAccess($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface|\ProxyManager\Proxy\ValueHolderInterface */
$newValue = uniqid();
$proxy->$publicProperty = $newValue;
$this->assertSame($newValue, $proxy->$publicProperty);
$this->assertSame($newValue, $proxy->getWrappedValueHolderValue()->$publicProperty);
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyExistence($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface|\ProxyManager\Proxy\ValueHolderInterface */
$this->assertSame(isset($instance->$publicProperty), isset($proxy->$publicProperty));
$this->assertEquals($instance, $proxy->getWrappedValueHolderValue());
$proxy->getWrappedValueHolderValue()->$publicProperty = null;
$this->assertFalse(isset($proxy->$publicProperty));
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyUnset($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\AccessInterceptorInterface|\ProxyManager\Proxy\ValueHolderInterface */
$instance = $proxy->getWrappedValueHolderValue() ? $proxy->getWrappedValueHolderValue() : $instance;
unset($proxy->$publicProperty);
$this->assertFalse(isset($instance->$publicProperty));
$this->assertFalse(isset($proxy->$publicProperty));
}
/**
* Verifies that accessing a public property containing an array behaves like in a normal context
*/
public function testCanWriteToArrayKeysInPublicProperty()
{
$instance = new ClassWithPublicArrayProperty();
$className = get_class($instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicArrayProperty */
$proxy = new $proxyName($instance);
$proxy->arrayProperty['foo'] = 'bar';
$this->assertSame('bar', $proxy->arrayProperty['foo']);
$proxy->arrayProperty = array('tab' => 'taz');
$this->assertSame(array('tab' => 'taz'), $proxy->arrayProperty);
}
/**
* Verifies that public properties retrieved via `__get` don't get modified in the object state
*/
public function testWillNotModifyRetrievedPublicProperties()
{
$instance = new ClassWithPublicProperties();
$className = get_class($instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicProperties */
$proxy = new $proxyName($instance);
$variable = $proxy->property0;
$this->assertSame('property0', $variable);
$variable = 'foo';
$this->assertSame('property0', $proxy->property0);
}
/**
* Verifies that public properties references retrieved via `__get` modify in the object state
*/
public function testWillModifyByRefRetrievedPublicProperties()
{
$instance = new ClassWithPublicProperties();
$className = get_class($instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicProperties */
$proxy = new $proxyName($instance);
$variable = & $proxy->property0;
$this->assertSame('property0', $variable);
$variable = 'foo';
$this->assertSame('foo', $proxy->property0);
}
/**
* Generates a proxy for the given class name, and retrieves its class name
*
* @param string $parentClassName
*
* @return string
*/
private function generateProxy($parentClassName)
{
$generatedClassName = __NAMESPACE__ . '\\' . UniqueIdentifierGenerator::getIdentifier('Foo');
$generator = new AccessInterceptorValueHolderGenerator();
$generatedClass = new ClassGenerator($generatedClassName);
$strategy = new EvaluatingGeneratorStrategy();
$generator->generate(new ReflectionClass($parentClassName), $generatedClass);
$strategy->generate($generatedClass);
return $generatedClassName;
}
/**
* Generates a list of object | invoked method | parameters | expected result
*
* @return array
*/
public function getProxyMethods()
{
$selfHintParam = new ClassWithSelfHint();
$data = array(
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicMethod',
array(),
'publicMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicTypeHintedMethod',
array('param' => new \stdClass()),
'publicTypeHintedMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicByReferenceMethod',
array(),
'publicByReferenceMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseInterface',
new BaseClass(),
'publicMethod',
array(),
'publicMethodDefault'
),
);
if (PHP_VERSION_ID >= 50401) {
// PHP < 5.4.1 misbehaves, throwing strict standards, see https://bugs.php.net/bug.php?id=60573
$data[] = array(
'ProxyManagerTestAsset\\ClassWithSelfHint',
new ClassWithSelfHint(),
'selfHintMethod',
array('parameter' => $selfHintParam),
$selfHintParam
);
}
return $data;
}
/**
* Generates proxies and instances with a public property to feed to the property accessor methods
*
* @return array
*/
public function getPropertyAccessProxies()
{
$instance1 = new BaseClass();
$proxyName1 = $this->generateProxy(get_class($instance1));
$instance2 = new BaseClass();
$proxyName2 = $this->generateProxy(get_class($instance2));
return array(
array(
$instance1,
new $proxyName1($instance1),
'publicProperty',
'publicPropertyDefault',
),
array(
$instance2,
unserialize(serialize(new $proxyName2($instance2))),
'publicProperty',
'publicPropertyDefault',
),
);
}
}

View File

@@ -1,196 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
/**
* Base performance test logic for lazy loading proxies
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Performance
* @coversNothing
*/
abstract class BaseLazyLoadingPerformanceTest extends BasePerformanceTest
{
/**
* @param string $className
* @param object[] $instances
* @param \ProxyManager\Proxy\LazyLoadingInterface[] $proxies
* @param string $methodName
* @param array $parameters
*/
protected function profileMethodAccess($className, array $instances, array $proxies, $methodName, array $parameters)
{
$iterations = count($instances);
$this->startCapturing();
foreach ($instances as $instance) {
call_user_func_array(array($instance, $methodName), $parameters);
}
$baseProfile = $this->endCapturing(
$iterations . ' calls to ' . $className . '#' . $methodName . ': %fms / %fKb'
);
$this->startCapturing();
foreach ($proxies as $proxy) {
call_user_func_array(array($proxy, $methodName), $parameters);
}
$proxyProfile = $this->endCapturing(
$iterations . ' calls to proxied ' . $className . '#' . $methodName . ': %fms / %fKb'
);
$this->compareProfile($baseProfile, $proxyProfile);
}
/**
* @param string $className
* @param object[] $instances
* @param \ProxyManager\Proxy\LazyLoadingInterface[] $proxies
* @param string $property
*/
protected function profilePropertyWrites($className, array $instances, array $proxies, $property)
{
$iterations = count($instances);
$this->startCapturing();
foreach ($instances as $instance) {
$instance->$property = 'foo';
}
$baseProfile = $this->endCapturing(
$iterations . ' writes of ' . $className . '::' . $property . ': %fms / %fKb'
);
$this->startCapturing();
foreach ($proxies as $proxy) {
$proxy->$property = 'foo';
}
$proxyProfile = $this->endCapturing(
$iterations . ' writes of proxied ' . $className . '::' . $property . ': %fms / %fKb'
);
$this->compareProfile($baseProfile, $proxyProfile);
}
/**
* @param string $className
* @param object[] $instances
* @param \ProxyManager\Proxy\LazyLoadingInterface[] $proxies
* @param string $property
*/
protected function profilePropertyReads($className, array $instances, array $proxies, $property)
{
$iterations = count($instances);
$this->startCapturing();
foreach ($instances as $instance) {
$instance->$property;
}
$baseProfile = $this->endCapturing(
$iterations . ' reads of ' . $className . '::' . $property . ': %fms / %fKb'
);
$this->startCapturing();
foreach ($proxies as $proxy) {
$proxy->$property;
}
$proxyProfile = $this->endCapturing(
$iterations . ' reads of proxied ' . $className . '::' . $property . ': %fms / %fKb'
);
$this->compareProfile($baseProfile, $proxyProfile);
}
/**
* @param string $className
* @param object[] $instances
* @param \ProxyManager\Proxy\LazyLoadingInterface[] $proxies
* @param string $property
*/
protected function profilePropertyIsset($className, array $instances, array $proxies, $property)
{
$iterations = count($instances);
$this->startCapturing();
foreach ($instances as $instance) {
isset($instance->$property);
}
$baseProfile = $this->endCapturing(
$iterations . ' isset of ' . $className . '::' . $property . ': %fms / %fKb'
);
$this->startCapturing();
foreach ($proxies as $proxy) {
isset($proxy->$property);
}
$proxyProfile = $this->endCapturing(
$iterations . ' isset of proxied ' . $className . '::' . $property . ': %fms / %fKb'
);
$this->compareProfile($baseProfile, $proxyProfile);
}
/**
* @param string $className
* @param object[] $instances
* @param \ProxyManager\Proxy\LazyLoadingInterface[] $proxies
* @param string $property
*/
protected function profilePropertyUnset($className, array $instances, array $proxies, $property)
{
$iterations = count($instances);
$this->startCapturing();
foreach ($instances as $instance) {
unset($instance->$property);
}
$baseProfile = $this->endCapturing(
$iterations . ' unset of ' . $className . '::' . $property . ': %fms / %fKb'
);
$this->startCapturing();
foreach ($proxies as $proxy) {
unset($proxy->$property);
}
$proxyProfile = $this->endCapturing(
$iterations . ' unset of proxied ' . $className . '::' . $property . ': %fms / %fKb'
);
$this->compareProfile($baseProfile, $proxyProfile);
}
/**
* Generates a proxy for the given class name, and retrieves its class name
*
* @param string $parentClassName
*
* @return string
*/
abstract protected function generateProxy($parentClassName);
}

View File

@@ -1,101 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use PHPUnit_Framework_TestCase;
/**
* Base performance test logic
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Performance
* @coversNothing
*/
abstract class BasePerformanceTest extends PHPUnit_Framework_TestCase
{
/**
* @var float time when last capture was started
*/
private $startTime = 0;
/**
* @var int bytes when last capture was started
*/
private $startMemory = 0;
/**
* {@inheritDoc}
*/
public static function setUpBeforeClass()
{
$header = "Performance test - " . get_called_class() . ":";
echo "\n\n" . str_repeat('=', strlen($header)) . "\n" . $header . "\n\n";
}
/**
* Start profiler snapshot
*/
protected function startCapturing()
{
$this->startMemory = memory_get_usage();
$this->startTime = microtime(true);
}
/**
* Echo current profiler output
*
* @param string $messageTemplate
*
* @return array
*/
protected function endCapturing($messageTemplate)
{
$time = microtime(true) - $this->startTime;
$memory = memory_get_usage() - $this->startMemory;
if (gc_enable()) {
gc_collect_cycles();
}
echo sprintf($messageTemplate, $time, $memory / 1024) . "\n";
return array(
'time' => $time,
'memory' => $memory
);
}
/**
* Display comparison between two profiles
*
* @param array $baseProfile
* @param array $proxyProfile
*/
protected function compareProfile(array $baseProfile, array $proxyProfile)
{
$baseMemory = max(1, $baseProfile['memory']);
$timeOverhead = (($proxyProfile['time'] / $baseProfile['time']) - 1) * 100;
$memoryOverhead = (($proxyProfile['memory'] / $baseMemory) - 1) * 100;
echo sprintf('Comparison time / memory: %.2f%% / %.2f%%', $timeOverhead, $memoryOverhead) . "\n\n";
}
}

View File

@@ -1,171 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use PHPUnit_Framework_TestCase;
use PHPUnit_Util_PHP;
use ReflectionClass;
/**
* Verifies that proxy-manager will not attempt to `eval()` code that will cause fatal errors
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Functional
* @coversNothing
*/
class FatalPreventionFunctionalTest extends PHPUnit_Framework_TestCase
{
private $template = <<<'PHP'
<?php
require_once %s;
$className = %s;
$generatedClass = new ProxyManager\Generator\ClassGenerator(uniqid('generated'));
$generatorStrategy = new ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy();
$classGenerator = new %s;
$classSignatureGenerator = new ProxyManager\Signature\ClassSignatureGenerator(
new ProxyManager\Signature\SignatureGenerator()
);
try {
$classGenerator->generate(new ReflectionClass($className), $generatedClass);
$classSignatureGenerator->addSignature($generatedClass, array('eval tests'));
$generatorStrategy->generate($generatedClass);
} catch (ProxyManager\Exception\ExceptionInterface $e) {
} catch (ReflectionException $e) {
}
echo 'SUCCESS: ' . %s;
PHP;
/**
* Verifies that code generation and evaluation will not cause fatals with any given class
*
* @param string $generatorClass an instantiable class (no arguments) implementing
* the {@see \ProxyManager\ProxyGenerator\ProxyGeneratorInterface}
* @param string $className a valid (existing/autoloadable) class name
*
* @dataProvider getTestedClasses
*/
public function testCodeGeneration($generatorClass, $className)
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('HHVM is just too slow for this kind of test right now.');
}
if (PHP_VERSION_ID < 50401) {
$this->markTestSkipped('Can\'t run this test suite on php < 5.4.1');
}
$runner = PHPUnit_Util_PHP::factory();
$code = sprintf(
$this->template,
var_export(realpath(__DIR__ . '/../../../vendor/autoload.php'), true),
var_export($className, true),
$generatorClass,
var_export($className, true)
);
$result = $runner->runJob($code, array('-n'));
if (('SUCCESS: ' . $className) !== $result['stdout']) {
$this->fail(sprintf(
"Crashed with class '%s' and generator '%s'.\n\nStdout:\n%s\nStderr:\n%s\nGenerated code:\n%s'",
$generatorClass,
$className,
$result['stdout'],
$result['stderr'],
$code
));
}
$this->assertSame('SUCCESS: ' . $className, $result['stdout']);
}
/**
* @return string[][]
*/
public function getTestedClasses()
{
$that = $this;
return call_user_func_array(
'array_merge',
array_map(
function ($generator) use ($that) {
return array_map(
function ($class) use ($generator) {
return array($generator, $class);
},
$that->getProxyTestedClasses()
);
},
array(
'ProxyManager\\ProxyGenerator\\AccessInterceptorScopeLocalizerGenerator',
'ProxyManager\\ProxyGenerator\\AccessInterceptorValueHolderGenerator',
'ProxyManager\\ProxyGenerator\\LazyLoadingGhostGenerator',
'ProxyManager\\ProxyGenerator\\LazyLoadingValueHolderGenerator',
'ProxyManager\\ProxyGenerator\\NullObjectGenerator',
'ProxyManager\\ProxyGenerator\\RemoteObjectGenerator',
)
)
);
}
/**
* @private (public only for PHP 5.3 compatibility)
*
* @return string[]
*/
public function getProxyTestedClasses()
{
$skippedPaths = array(
realpath(__DIR__ . '/../../src'),
realpath(__DIR__ . '/../../vendor'),
realpath(__DIR__ . '/../../tests/ProxyManagerTest'),
);
return array_filter(
get_declared_classes(),
function ($className) use ($skippedPaths) {
$reflectionClass = new ReflectionClass($className);
$fileName = $reflectionClass->getFileName();
if (! $fileName) {
return false;
}
$realPath = realpath($fileName);
foreach ($skippedPaths as $skippedPath) {
if (0 === strpos($realPath, $skippedPath)) {
// skip classes defined within ProxyManager, vendor or the test suite
return false;
}
}
return true;
}
);
}
}

View File

@@ -1,441 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use PHPUnit_Framework_TestCase;
use PHPUnit_Framework_MockObject_MockObject as Mock;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\Proxy\GhostObjectInterface;
use ProxyManager\ProxyGenerator\LazyLoadingGhostGenerator;
use ProxyManagerTestAsset\BaseClass;
use ProxyManagerTestAsset\ClassWithPublicArrayProperty;
use ProxyManagerTestAsset\ClassWithPublicProperties;
use ProxyManagerTestAsset\ClassWithProtectedProperties;
use ProxyManagerTestAsset\ClassWithPrivateProperties;
use ProxyManagerTestAsset\ClassWithSelfHint;
use ReflectionClass;
use ReflectionProperty;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\LazyLoadingGhostGenerator} produced objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Functional
* @coversNothing
*/
class LazyLoadingGhostFunctionalTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider getProxyMethods
*/
public function testMethodCalls($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\GhostObjectInterface|BaseClass */
$proxy = new $proxyName($this->createInitializer($className, $instance));
$this->assertFalse($proxy->isProxyInitialized());
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$this->assertTrue($proxy->isProxyInitialized());
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsAfterUnSerialization($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\GhostObjectInterface|BaseClass */
$proxy = unserialize(serialize(new $proxyName($this->createInitializer($className, $instance))));
$this->assertTrue($proxy->isProxyInitialized());
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsAfterCloning($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\GhostObjectInterface|BaseClass */
$proxy = new $proxyName($this->createInitializer($className, $instance));
$cloned = clone $proxy;
$this->assertTrue($cloned->isProxyInitialized());
$this->assertSame($expectedValue, call_user_func_array(array($cloned, $method), $params));
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyReadAccess($instance, $proxy, $publicProperty, $propertyValue)
{
/* @var $proxy \ProxyManager\Proxy\GhostObjectInterface */
$this->assertSame($propertyValue, $proxy->$publicProperty);
$this->assertTrue($proxy->isProxyInitialized());
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyWriteAccess($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\GhostObjectInterface */
$newValue = uniqid();
$proxy->$publicProperty = $newValue;
$this->assertTrue($proxy->isProxyInitialized());
$this->assertSame($newValue, $proxy->$publicProperty);
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyExistence($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\GhostObjectInterface */
$this->assertSame(isset($instance->$publicProperty), isset($proxy->$publicProperty));
$this->assertTrue($proxy->isProxyInitialized());
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyAbsence($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\GhostObjectInterface */
$proxy->$publicProperty = null;
$this->assertFalse(isset($proxy->$publicProperty));
$this->assertTrue($proxy->isProxyInitialized());
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyUnset($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\GhostObjectInterface */
unset($proxy->$publicProperty);
$this->assertTrue($proxy->isProxyInitialized());
$this->assertTrue(isset($instance->$publicProperty));
$this->assertFalse(isset($proxy->$publicProperty));
}
/**
* Verifies that accessing a public property containing an array behaves like in a normal context
*/
public function testCanWriteToArrayKeysInPublicProperty()
{
$instance = new ClassWithPublicArrayProperty();
$className = get_class($instance);
$initializer = $this->createInitializer($className, $instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicArrayProperty */
$proxy = new $proxyName($initializer);
$proxy->arrayProperty['foo'] = 'bar';
$this->assertSame('bar', $proxy->arrayProperty['foo']);
$proxy->arrayProperty = array('tab' => 'taz');
$this->assertSame(array('tab' => 'taz'), $proxy->arrayProperty);
}
/**
* Verifies that public properties retrieved via `__get` don't get modified in the object itself
*/
public function testWillNotModifyRetrievedPublicProperties()
{
$instance = new ClassWithPublicProperties();
$className = get_class($instance);
$initializer = $this->createInitializer($className, $instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicProperties */
$proxy = new $proxyName($initializer);
$variable = $proxy->property0;
$this->assertSame('property0', $variable);
$variable = 'foo';
$this->assertSame('property0', $proxy->property0);
}
/**
* Verifies that public properties references retrieved via `__get` modify in the object state
*/
public function testWillModifyByRefRetrievedPublicProperties()
{
$instance = new ClassWithPublicProperties();
$className = get_class($instance);
$initializer = $this->createInitializer($className, $instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicProperties */
$proxy = new $proxyName($initializer);
$variable = & $proxy->property0;
$this->assertSame('property0', $variable);
$variable = 'foo';
$this->assertSame('foo', $proxy->property0);
}
public function testKeepsInitializerWhenNotOverwitten()
{
$instance = new BaseClass();
$proxyName = $this->generateProxy(get_class($instance));
$initializer = function () {
};
/* @var $proxy \ProxyManager\Proxy\GhostObjectInterface */
$proxy = new $proxyName($initializer);
$proxy->initializeProxy();
$this->assertSame($initializer, $proxy->getProxyInitializer());
}
/**
* Verifies that public properties are not being initialized multiple times
*/
public function testKeepsInitializedPublicProperties()
{
$instance = new BaseClass();
$proxyName = $this->generateProxy(get_class($instance));
$initializer = function (BaseClass $proxy, $method, $parameters, & $initializer) {
$initializer = null;
$proxy->publicProperty = 'newValue';
};
/* @var $proxy \ProxyManager\Proxy\GhostObjectInterface|BaseClass */
$proxy = new $proxyName($initializer);
$proxy->initializeProxy();
$this->assertSame('newValue', $proxy->publicProperty);
$proxy->publicProperty = 'otherValue';
$proxy->initializeProxy();
$this->assertSame('otherValue', $proxy->publicProperty);
}
/**
* Verifies that properties' default values are preserved
*/
public function testPublicPropertyDefaultWillBePreserved()
{
$instance = new ClassWithPublicProperties();
$proxyName = $this->generateProxy(get_class($instance));
/* @var $proxy ClassWithPublicProperties */
$proxy = new $proxyName(function () {
});
$this->assertSame('property0', $proxy->property0);
}
/**
* Verifies that protected properties' default values are preserved
*/
public function testProtectedPropertyDefaultWillBePreserved()
{
$instance = new ClassWithProtectedProperties();
$proxyName = $this->generateProxy(get_class($instance));
/* @var $proxy ClassWithProtectedProperties */
$proxy = new $proxyName(function () {
});
// Check protected property via reflection
$reflectionProperty = new ReflectionProperty($instance, 'property0');
$reflectionProperty->setAccessible(true);
$this->assertSame('property0', $reflectionProperty->getValue($proxy));
}
/**
* Verifies that private properties' default values are preserved
*/
public function testPrivatePropertyDefaultWillBePreserved()
{
$instance = new ClassWithPrivateProperties();
$proxyName = $this->generateProxy(get_class($instance));
/* @var $proxy ClassWithPrivateProperties */
$proxy = new $proxyName(function () {
});
// Check protected property via reflection
$reflectionProperty = new ReflectionProperty($instance, 'property0');
$reflectionProperty->setAccessible(true);
$this->assertSame('property0', $reflectionProperty->getValue($proxy));
}
/**
* Generates a proxy for the given class name, and retrieves its class name
*
* @param string $parentClassName
*
* @return string
*/
private function generateProxy($parentClassName)
{
$generatedClassName = __NAMESPACE__ . '\\' . UniqueIdentifierGenerator::getIdentifier('Foo');
$generator = new LazyLoadingGhostGenerator();
$generatedClass = new ClassGenerator($generatedClassName);
$strategy = new EvaluatingGeneratorStrategy();
$generator->generate(new ReflectionClass($parentClassName), $generatedClass);
$strategy->generate($generatedClass);
return $generatedClassName;
}
/**
* @param string $className
* @param object $realInstance
* @param Mock $initializerMatcher
*
* @return \Closure
*/
private function createInitializer($className, $realInstance, Mock $initializerMatcher = null)
{
if (null === $initializerMatcher) {
$initializerMatcher = $this->getMock('stdClass', array('__invoke'));
$initializerMatcher
->expects($this->once())
->method('__invoke')
->with(
$this->logicalAnd(
$this->isInstanceOf('ProxyManager\\Proxy\\GhostObjectInterface'),
$this->isInstanceOf($className)
)
);
}
$initializerMatcher = $initializerMatcher ?: $this->getMock('stdClass', array('__invoke'));
return function (
GhostObjectInterface $proxy,
$method,
$params,
& $initializer
) use (
$initializerMatcher,
$realInstance
) {
$initializer = null;
$reflectionClass = new ReflectionClass($realInstance);
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$property->setValue($proxy, $property->getValue($realInstance));
}
$initializerMatcher->__invoke($proxy, $method, $params);
};
}
/**
* Generates a list of object | invoked method | parameters | expected result
*
* @return array
*/
public function getProxyMethods()
{
$selfHintParam = new ClassWithSelfHint();
$data = array(
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicMethod',
array(),
'publicMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicTypeHintedMethod',
array(new \stdClass()),
'publicTypeHintedMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicByReferenceMethod',
array(),
'publicByReferenceMethodDefault'
),
);
if (PHP_VERSION_ID >= 50401) {
// PHP < 5.4.1 misbehaves, throwing strict standards, see https://bugs.php.net/bug.php?id=60573
$data[] = array(
'ProxyManagerTestAsset\\ClassWithSelfHint',
new ClassWithSelfHint(),
'selfHintMethod',
array('parameter' => $selfHintParam),
$selfHintParam
);
}
return $data;
}
/**
* Generates proxies and instances with a public property to feed to the property accessor methods
*
* @return array
*/
public function getPropertyAccessProxies()
{
$instance1 = new BaseClass();
$proxyName1 = $this->generateProxy(get_class($instance1));
$instance2 = new BaseClass();
$proxyName2 = $this->generateProxy(get_class($instance2));
return array(
array(
$instance1,
new $proxyName1($this->createInitializer('ProxyManagerTestAsset\\BaseClass', $instance1)),
'publicProperty',
'publicPropertyDefault',
),
array(
$instance2,
unserialize(
serialize(new $proxyName2($this->createInitializer('ProxyManagerTestAsset\\BaseClass', $instance2)))
),
'publicProperty',
'publicPropertyDefault',
),
);
}
}

View File

@@ -1,160 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\Proxy\GhostObjectInterface;
use ProxyManager\ProxyGenerator\LazyLoadingGhostGenerator;
use ReflectionClass;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\LazyLoadingGhostGenerator} produced objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Performance
* @coversNothing
*/
class LazyLoadingGhostPerformanceTest extends BaseLazyLoadingPerformanceTest
{
/**
* @outputBuffering
* @dataProvider getTestedClasses
*
* @param string $className
* @param array $methods
* @param array $properties
* @param \ReflectionProperty[] $reflectionProperties
*
* @return void
*/
public function testProxyInstantiationPerformance(
$className,
array $methods,
array $properties,
array $reflectionProperties
) {
$proxyName = $this->generateProxy($className);
$iterations = 20000;
$instances = array();
/* @var $proxies \ProxyManager\Proxy\GhostObjectInterface[] */
$proxies = array();
$realInstance = new $className();
$initializer = function (
GhostObjectInterface $proxy,
$method,
$params,
& $initializer
) use (
$reflectionProperties,
$realInstance
) {
$initializer = null;
foreach ($reflectionProperties as $reflectionProperty) {
$reflectionProperty->setValue($proxy, $reflectionProperty->getValue($realInstance));
}
return true;
};
$this->startCapturing();
for ($i = 0; $i < $iterations; $i += 1) {
$instances[] = new $className();
}
$baseProfile = $this->endCapturing(
'Instantiation for ' . $iterations . ' objects of type ' . $className . ': %fms / %fKb'
);
$this->startCapturing();
for ($i = 0; $i < $iterations; $i += 1) {
$proxies[] = new $proxyName($initializer);
}
$proxyProfile = $this->endCapturing(
'Instantiation for ' . $iterations . ' proxies of type ' . $className . ': %fms / %fKb'
);
$this->compareProfile($baseProfile, $proxyProfile);
$this->startCapturing();
foreach ($proxies as $proxy) {
$proxy->initializeProxy();
}
$this->endCapturing('Initialization of ' . $iterations . ' proxies of type ' . $className . ': %fms / %fKb');
foreach ($methods as $methodName => $parameters) {
$this->profileMethodAccess($className, $instances, $proxies, $methodName, $parameters);
}
foreach ($properties as $property) {
$this->profilePropertyWrites($className, $instances, $proxies, $property);
$this->profilePropertyReads($className, $instances, $proxies, $property);
$this->profilePropertyIsset($className, $instances, $proxies, $property);
$this->profilePropertyUnset($className, $instances, $proxies, $property);
}
}
/**
* @return array
*/
public function getTestedClasses()
{
$testedClasses = array(
array('stdClass', array(), array()),
array('ProxyManagerTestAsset\\BaseClass', array('publicMethod' => array()), array('publicProperty')),
);
foreach ($testedClasses as $key => $testedClass) {
$reflectionProperties = array();
$reflectionClass = new ReflectionClass($testedClass[0]);
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$reflectionProperties[$property->getName()] = $property;
}
$testedClasses[$key][] = $reflectionProperties;
}
return $testedClasses;
}
/**
* {@inheritDoc}
*/
protected function generateProxy($parentClassName)
{
$generatedClassName = __NAMESPACE__ . '\\' . UniqueIdentifierGenerator::getIdentifier('Foo');
$generator = new LazyLoadingGhostGenerator();
$generatedClass = new ClassGenerator($generatedClassName);
$strategy = new EvaluatingGeneratorStrategy();
$generator->generate(new ReflectionClass($parentClassName), $generatedClass);
$strategy->generate($generatedClass);
return $generatedClassName;
}
}

View File

@@ -1,386 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use PHPUnit_Framework_TestCase;
use PHPUnit_Framework_MockObject_MockObject as Mock;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\Proxy\VirtualProxyInterface;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator;
use ProxyManagerTestAsset\BaseClass;
use ProxyManagerTestAsset\ClassWithPublicArrayProperty;
use ProxyManagerTestAsset\ClassWithPublicProperties;
use ProxyManagerTestAsset\ClassWithSelfHint;
use ReflectionClass;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator} produced objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Functional
* @coversNothing
*/
class LazyLoadingValueHolderFunctionalTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider getProxyMethods
*/
public function testMethodCalls($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\VirtualProxyInterface|BaseClass */
$proxy = new $proxyName($this->createInitializer($className, $instance));
$this->assertFalse($proxy->isProxyInitialized());
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$this->assertTrue($proxy->isProxyInitialized());
$this->assertSame($instance, $proxy->getWrappedValueHolderValue());
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsAfterUnSerialization($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\VirtualProxyInterface|BaseClass */
$proxy = unserialize(serialize(new $proxyName($this->createInitializer($className, $instance))));
$this->assertTrue($proxy->isProxyInitialized());
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
$this->assertEquals($instance, $proxy->getWrappedValueHolderValue());
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsAfterCloning($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\VirtualProxyInterface|BaseClass */
$proxy = new $proxyName($this->createInitializer($className, $instance));
$cloned = clone $proxy;
$this->assertTrue($cloned->isProxyInitialized());
$this->assertNotSame($proxy->getWrappedValueHolderValue(), $cloned->getWrappedValueHolderValue());
$this->assertSame($expectedValue, call_user_func_array(array($cloned, $method), $params));
$this->assertEquals($instance, $cloned->getWrappedValueHolderValue());
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyReadAccess($instance, $proxy, $publicProperty, $propertyValue)
{
/* @var $proxy \ProxyManager\Proxy\VirtualProxyInterface|BaseClass */
$this->assertSame($propertyValue, $proxy->$publicProperty);
$this->assertTrue($proxy->isProxyInitialized());
$this->assertEquals($instance, $proxy->getWrappedValueHolderValue());
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyWriteAccess($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\VirtualProxyInterface|BaseClass */
$newValue = uniqid();
$proxy->$publicProperty = $newValue;
$this->assertTrue($proxy->isProxyInitialized());
$this->assertSame($newValue, $proxy->$publicProperty);
$this->assertSame($newValue, $proxy->getWrappedValueHolderValue()->$publicProperty);
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyExistence($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\VirtualProxyInterface|BaseClass */
$this->assertSame(isset($instance->$publicProperty), isset($proxy->$publicProperty));
$this->assertTrue($proxy->isProxyInitialized());
$this->assertEquals($instance, $proxy->getWrappedValueHolderValue());
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyAbsence($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\VirtualProxyInterface|BaseClass */
$instance = $proxy->getWrappedValueHolderValue() ? $proxy->getWrappedValueHolderValue() : $instance;
$instance->$publicProperty = null;
$this->assertFalse(isset($proxy->$publicProperty));
$this->assertTrue($proxy->isProxyInitialized());
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyUnset($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\VirtualProxyInterface|BaseClass */
$instance = $proxy->getWrappedValueHolderValue() ? $proxy->getWrappedValueHolderValue() : $instance;
unset($proxy->$publicProperty);
$this->assertTrue($proxy->isProxyInitialized());
$this->assertFalse(isset($instance->$publicProperty));
$this->assertFalse(isset($proxy->$publicProperty));
}
/**
* Verifies that accessing a public property containing an array behaves like in a normal context
*/
public function testCanWriteToArrayKeysInPublicProperty()
{
$instance = new ClassWithPublicArrayProperty();
$className = get_class($instance);
$initializer = $this->createInitializer($className, $instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicArrayProperty */
$proxy = new $proxyName($initializer);
$proxy->arrayProperty['foo'] = 'bar';
$this->assertSame('bar', $proxy->arrayProperty['foo']);
$proxy->arrayProperty = array('tab' => 'taz');
$this->assertSame(array('tab' => 'taz'), $proxy->arrayProperty);
}
/**
* Verifies that public properties retrieved via `__get` don't get modified in the object itself
*/
public function testWillNotModifyRetrievedPublicProperties()
{
$instance = new ClassWithPublicProperties();
$className = get_class($instance);
$initializer = $this->createInitializer($className, $instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicProperties */
$proxy = new $proxyName($initializer);
$variable = $proxy->property0;
$this->assertSame('property0', $variable);
$variable = 'foo';
$this->assertSame('property0', $proxy->property0);
}
/**
* Verifies that public properties references retrieved via `__get` modify in the object state
*/
public function testWillModifyByRefRetrievedPublicProperties()
{
$instance = new ClassWithPublicProperties();
$className = get_class($instance);
$initializer = $this->createInitializer($className, $instance);
$proxyName = $this->generateProxy($className);
/* @var $proxy ClassWithPublicProperties */
$proxy = new $proxyName($initializer);
$variable = & $proxy->property0;
$this->assertSame('property0', $variable);
$variable = 'foo';
$this->assertSame('foo', $proxy->property0);
}
/**
* @group 16
*
* Verifies that initialization of a value holder proxy may happen multiple times
*/
public function testWillAllowMultipleProxyInitialization()
{
$proxyClass = $this->generateProxy('ProxyManagerTestAsset\\BaseClass');
$counter = 0;
$initializer = function (& $wrappedInstance) use (& $counter) {
$wrappedInstance = new BaseClass();
$wrappedInstance->publicProperty = (string) ($counter += 1);
};
/* @var $proxy BaseClass */
$proxy = new $proxyClass($initializer);
$this->assertSame('1', $proxy->publicProperty);
$this->assertSame('2', $proxy->publicProperty);
$this->assertSame('3', $proxy->publicProperty);
}
/**
* Generates a proxy for the given class name, and retrieves its class name
*
* @param string $parentClassName
*
* @return string
*/
private function generateProxy($parentClassName)
{
$generatedClassName = __NAMESPACE__ . '\\' . UniqueIdentifierGenerator::getIdentifier('Foo');
$generator = new LazyLoadingValueHolderGenerator();
$generatedClass = new ClassGenerator($generatedClassName);
$strategy = new EvaluatingGeneratorStrategy();
$generator->generate(new ReflectionClass($parentClassName), $generatedClass);
$strategy->generate($generatedClass);
return $generatedClassName;
}
/**
* @param string $className
* @param object $realInstance
* @param Mock $initializerMatcher
*
* @return \Closure
*/
private function createInitializer($className, $realInstance, Mock $initializerMatcher = null)
{
if (null === $initializerMatcher) {
$initializerMatcher = $this->getMock('stdClass', array('__invoke'));
$initializerMatcher
->expects($this->once())
->method('__invoke')
->with(
$this->logicalAnd(
$this->isInstanceOf('ProxyManager\\Proxy\\VirtualProxyInterface'),
$this->isInstanceOf($className)
),
$realInstance
);
}
$initializerMatcher = $initializerMatcher ?: $this->getMock('stdClass', array('__invoke'));
return function (
& $wrappedObject,
VirtualProxyInterface $proxy,
$method,
$params,
& $initializer
) use (
$initializerMatcher,
$realInstance
) {
$initializer = null;
$wrappedObject = $realInstance;
$initializerMatcher->__invoke($proxy, $wrappedObject, $method, $params);
};
}
/**
* Generates a list of object | invoked method | parameters | expected result
*
* @return array
*/
public function getProxyMethods()
{
$selfHintParam = new ClassWithSelfHint();
$data = array(
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicMethod',
array(),
'publicMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicTypeHintedMethod',
array(new \stdClass()),
'publicTypeHintedMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicByReferenceMethod',
array(),
'publicByReferenceMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseInterface',
new BaseClass(),
'publicMethod',
array(),
'publicMethodDefault'
),
);
if (PHP_VERSION_ID >= 50401) {
// PHP < 5.4.1 misbehaves, throwing strict standards, see https://bugs.php.net/bug.php?id=60573
$data[] = array(
'ProxyManagerTestAsset\\ClassWithSelfHint',
new ClassWithSelfHint(),
'selfHintMethod',
array('parameter' => $selfHintParam),
$selfHintParam
);
}
return $data;
}
/**
* Generates proxies and instances with a public property to feed to the property accessor methods
*
* @return array
*/
public function getPropertyAccessProxies()
{
$instance1 = new BaseClass();
$proxyName1 = $this->generateProxy(get_class($instance1));
$instance2 = new BaseClass();
$proxyName2 = $this->generateProxy(get_class($instance2));
return array(
array(
$instance1,
new $proxyName1($this->createInitializer('ProxyManagerTestAsset\\BaseClass', $instance1)),
'publicProperty',
'publicPropertyDefault',
),
array(
$instance2,
unserialize(
serialize(new $proxyName2($this->createInitializer('ProxyManagerTestAsset\\BaseClass', $instance2)))
),
'publicProperty',
'publicPropertyDefault',
),
);
}
}

View File

@@ -1,134 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\Proxy\VirtualProxyInterface;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator;
use ReflectionClass;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator} produced objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Performance
* @coversNothing
*/
class LazyLoadingValueHolderPerformanceTest extends BaseLazyLoadingPerformanceTest
{
/**
* @outputBuffering
* @dataProvider getTestedClasses
*
* @param string $className
* @param array $methods
* @param array $properties
*
* @return void
*/
public function testProxyInstantiationPerformance($className, array $methods, array $properties)
{
$proxyName = $this->generateProxy($className);
$iterations = 20000;
$instances = array();
/* @var $proxies \ProxyManager\Proxy\VirtualProxyInterface[] */
$proxies = array();
$initializer = function (
& $valueHolder,
VirtualProxyInterface $proxy,
$method,
$params,
& $initializer
) use ($className) {
$initializer = null;
$valueHolder = new $className();
return true;
};
$this->startCapturing();
for ($i = 0; $i < $iterations; $i += 1) {
$instances[] = new $className();
}
$baseProfile = $this->endCapturing(
'Instantiation for ' . $iterations . ' objects of type ' . $className . ': %fms / %fKb'
);
$this->startCapturing();
for ($i = 0; $i < $iterations; $i += 1) {
$proxies[] = new $proxyName($initializer);
}
$proxyProfile = $this->endCapturing(
'Instantiation for ' . $iterations . ' proxies of type ' . $className . ': %fms / %fKb'
);
$this->compareProfile($baseProfile, $proxyProfile);
$this->startCapturing();
foreach ($proxies as $proxy) {
$proxy->initializeProxy();
}
$this->endCapturing('Initialization of ' . $iterations . ' proxies of type ' . $className . ': %fms / %fKb');
foreach ($methods as $methodName => $parameters) {
$this->profileMethodAccess($className, $instances, $proxies, $methodName, $parameters);
}
foreach ($properties as $property) {
$this->profilePropertyWrites($className, $instances, $proxies, $property);
$this->profilePropertyReads($className, $instances, $proxies, $property);
$this->profilePropertyIsset($className, $instances, $proxies, $property);
$this->profilePropertyUnset($className, $instances, $proxies, $property);
}
}
/**
* @return array
*/
public function getTestedClasses()
{
return array(
array('stdClass', array(), array()),
array('ProxyManagerTestAsset\\BaseClass', array('publicMethod' => array()), array('publicProperty')),
);
}
/**
* {@inheritDoc}
*/
protected function generateProxy($parentClassName)
{
$generatedClassName = __NAMESPACE__ . '\\' . UniqueIdentifierGenerator::getIdentifier('Foo');
$generator = new LazyLoadingValueHolderGenerator();
$generatedClass = new ClassGenerator($generatedClassName);
$strategy = new EvaluatingGeneratorStrategy();
$generator->generate(new ReflectionClass($parentClassName), $generatedClass);
$strategy->generate($generatedClass);
return $generatedClassName;
}
}

View File

@@ -1,123 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\AccessInterceptorScopeLocalizerFactory;
use ProxyManager\Factory\AccessInterceptorValueHolderFactory;
use ProxyManager\Factory\LazyLoadingGhostFactory;
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use ReflectionClass;
use ReflectionProperty;
/**
* Verifies that proxy factories don't conflict with each other when generating proxies
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @link https://github.com/Ocramius/ProxyManager/issues/10
*
* @group Functional
* @group issue-10
* @coversNothing
*/
class MultipleProxyGenerationTest extends PHPUnit_Framework_TestCase
{
/**
* Verifies that proxies generated from different factories will retain their specific implementation
* and won't conflict
*
* @dataProvider getTestedClasses
*/
public function testCanGenerateMultipleDifferentProxiesForSameClass($className)
{
$skipScopeLocalizerTests = false;
$ghostProxyFactory = new LazyLoadingGhostFactory();
$virtualProxyFactory = new LazyLoadingValueHolderFactory();
$accessInterceptorFactory = new AccessInterceptorValueHolderFactory();
$accessInterceptorScopeLocalizerFactory = new AccessInterceptorScopeLocalizerFactory();
$initializer = function () {
};
$reflectionClass = new ReflectionClass($className);
if ((! method_exists('Closure', 'bind')) && $reflectionClass->getProperties(ReflectionProperty::IS_PRIVATE)) {
$skipScopeLocalizerTests = true;
}
$generated = array(
$ghostProxyFactory->createProxy($className, $initializer),
$virtualProxyFactory->createProxy($className, $initializer),
$accessInterceptorFactory->createProxy(new $className()),
);
if (! $skipScopeLocalizerTests) {
$generated[] = $accessInterceptorScopeLocalizerFactory->createProxy(new $className());
}
foreach ($generated as $key => $proxy) {
$this->assertInstanceOf($className, $proxy);
foreach ($generated as $comparedKey => $comparedProxy) {
if ($comparedKey === $key) {
continue;
}
$this->assertNotSame(get_class($comparedProxy), get_class($proxy));
}
}
$this->assertInstanceOf('ProxyManager\Proxy\GhostObjectInterface', $generated[0]);
$this->assertInstanceOf('ProxyManager\Proxy\VirtualProxyInterface', $generated[1]);
$this->assertInstanceOf('ProxyManager\Proxy\AccessInterceptorInterface', $generated[2]);
$this->assertInstanceOf('ProxyManager\Proxy\ValueHolderInterface', $generated[2]);
if (! $skipScopeLocalizerTests) {
$this->assertInstanceOf('ProxyManager\Proxy\AccessInterceptorInterface', $generated[3]);
}
}
/**
* @return string[][]
*/
public function getTestedClasses()
{
$data = array(
array('ProxyManagerTestAsset\\BaseClass'),
array('ProxyManagerTestAsset\\ClassWithMagicMethods'),
array('ProxyManagerTestAsset\\ClassWithFinalMethods'),
array('ProxyManagerTestAsset\\ClassWithFinalMagicMethods'),
array('ProxyManagerTestAsset\\ClassWithByRefMagicMethods'),
array('ProxyManagerTestAsset\\ClassWithMixedProperties'),
array('ProxyManagerTestAsset\\ClassWithPrivateProperties'),
array('ProxyManagerTestAsset\\ClassWithProtectedProperties'),
array('ProxyManagerTestAsset\\ClassWithPublicProperties'),
array('ProxyManagerTestAsset\\EmptyClass'),
array('ProxyManagerTestAsset\\HydratedObject'),
);
if (PHP_VERSION_ID >= 50401) {
// PHP < 5.4.1 misbehaves, throwing strict standards, see https://bugs.php.net/bug.php?id=60573
$data[] = array('ProxyManagerTestAsset\\ClassWithSelfHint');
}
return $data;
}
}

View File

@@ -1,223 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use PHPUnit_Framework_TestCase;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\ProxyGenerator\NullObjectGenerator;
use ProxyManagerTestAsset\BaseClass;
use ProxyManagerTestAsset\ClassWithSelfHint;
use ReflectionClass;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\NullObjectGenerator} produced objects
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*
* @group Functional
* @coversNothing
*/
class NullObjectFunctionalTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider getProxyMethods
*/
public function testMethodCalls($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\NullObjectInterface */
$proxy = new $proxyName();
$this->assertSame(null, call_user_func_array(array($proxy, $method), $params));
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsAfterUnSerialization($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\NullObjectInterface */
$proxy = unserialize(serialize(new $proxyName()));
$this->assertSame(null, call_user_func_array(array($proxy, $method), $params));
}
/**
* @dataProvider getProxyMethods
*/
public function testMethodCallsAfterCloning($className, $instance, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($className);
/* @var $proxy \ProxyManager\Proxy\NullObjectInterface */
$proxy = new $proxyName();
$cloned = clone $proxy;
$this->assertSame(null, call_user_func_array(array($cloned, $method), $params));
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyReadAccess($instance, $proxy, $publicProperty, $propertyValue)
{
/* @var $proxy \ProxyManager\Proxy\NullObjectInterface */
$this->assertSame(null, $proxy->$publicProperty);
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyWriteAccess($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\NullObjectInterface */
$newValue = uniqid();
$proxy->$publicProperty = $newValue;
$this->assertSame($newValue, $proxy->$publicProperty);
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyExistence($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\NullObjectInterface */
$this->assertSame(null, $proxy->$publicProperty);
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testPropertyUnset($instance, $proxy, $publicProperty)
{
/* @var $proxy \ProxyManager\Proxy\NullObjectInterface */
unset($proxy->$publicProperty);
$this->assertTrue(isset($instance->$publicProperty));
$this->assertFalse(isset($proxy->$publicProperty));
}
/**
* Generates a proxy for the given class name, and retrieves its class name
*
* @param string $parentClassName
*
* @return string
*/
private function generateProxy($parentClassName)
{
$generatedClassName = __NAMESPACE__ . '\\' . UniqueIdentifierGenerator::getIdentifier('Foo');
$generator = new NullObjectGenerator();
$generatedClass = new ClassGenerator($generatedClassName);
$strategy = new EvaluatingGeneratorStrategy();
$generator->generate(new ReflectionClass($parentClassName), $generatedClass);
$strategy->generate($generatedClass);
return $generatedClassName;
}
/**
* Generates a list of object | invoked method | parameters | expected result
*
* @return array
*/
public function getProxyMethods()
{
$selfHintParam = new ClassWithSelfHint();
$data = array(
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicMethod',
array(),
'publicMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicTypeHintedMethod',
array('param' => new \stdClass()),
'publicTypeHintedMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseClass',
new BaseClass(),
'publicByReferenceMethod',
array(),
'publicByReferenceMethodDefault'
),
array(
'ProxyManagerTestAsset\\BaseInterface',
new BaseClass(),
'publicMethod',
array(),
'publicMethodDefault'
),
);
if (PHP_VERSION_ID >= 50401) {
// PHP < 5.4.1 misbehaves, throwing strict standards, see https://bugs.php.net/bug.php?id=60573
$data[] = array(
'ProxyManagerTestAsset\\ClassWithSelfHint',
new ClassWithSelfHint(),
'selfHintMethod',
array('parameter' => $selfHintParam),
$selfHintParam
);
}
return $data;
}
/**
* Generates proxies and instances with a public property to feed to the property accessor methods
*
* @return array
*/
public function getPropertyAccessProxies()
{
$instance1 = new BaseClass();
$proxyName1 = $this->generateProxy(get_class($instance1));
$instance2 = new BaseClass();
$proxyName2 = $this->generateProxy(get_class($instance2));
return array(
array(
$instance1,
new $proxyName1($instance1),
'publicProperty',
'publicPropertyDefault',
),
array(
$instance2,
unserialize(serialize(new $proxyName2($instance2))),
'publicProperty',
'publicPropertyDefault',
),
);
}
}

View File

@@ -1,231 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Functional;
use PHPUnit_Framework_TestCase;
use ProxyManager\Factory\RemoteObject\Adapter\JsonRpc as JsonRpcAdapter;
use ProxyManager\Factory\RemoteObject\Adapter\XmlRpc as XmlRpcAdapter;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\ProxyGenerator\RemoteObjectGenerator;
use ProxyManagerTestAsset\ClassWithSelfHint;
use ProxyManagerTestAsset\RemoteProxy\Foo;
use ReflectionClass;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\RemoteObjectGenerator} produced objects
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*
* @group Functional
* @coversNothing
*/
class RemoteObjectFunctionalTest extends PHPUnit_Framework_TestCase
{
/**
* @param mixed $expectedValue
* @param string $method
* @param array $params
*
* @return XmlRpcAdapter
*/
protected function getXmlRpcAdapter($expectedValue, $method, array $params)
{
$client = $this
->getMockBuilder('Zend\Server\Client')
->setMethods(array('call'))
->getMock();
$client
->expects($this->any())
->method('call')
->with($this->stringEndsWith($method), $params)
->will($this->returnValue($expectedValue));
$adapter = new XmlRpcAdapter(
$client,
array(
'ProxyManagerTestAsset\RemoteProxy\Foo.foo'
=> 'ProxyManagerTestAsset\RemoteProxy\FooServiceInterface.foo'
)
);
return $adapter;
}
/**
* @param mixed $expectedValue
* @param string $method
* @param array $params
*
* @return JsonRpcAdapter
*/
protected function getJsonRpcAdapter($expectedValue, $method, array $params)
{
$client = $this
->getMockBuilder('Zend\Server\Client')
->setMethods(array('call'))
->getMock();
$client
->expects($this->any())
->method('call')
->with($this->stringEndsWith($method), $params)
->will($this->returnValue($expectedValue));
$adapter = new JsonRpcAdapter(
$client,
array(
'ProxyManagerTestAsset\RemoteProxy\Foo.foo'
=> 'ProxyManagerTestAsset\RemoteProxy\FooServiceInterface.foo'
)
);
return $adapter;
}
/**
* @dataProvider getProxyMethods
*/
public function testXmlRpcMethodCalls($instanceOrClassname, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($instanceOrClassname);
/* @var $proxy \ProxyManager\Proxy\RemoteObjectInterface */
$proxy = new $proxyName($this->getXmlRpcAdapter($expectedValue, $method, $params));
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
}
/**
* @dataProvider getProxyMethods
*/
public function testJsonRpcMethodCalls($instanceOrClassname, $method, $params, $expectedValue)
{
$proxyName = $this->generateProxy($instanceOrClassname);
/* @var $proxy \ProxyManager\Proxy\RemoteObjectInterface */
$proxy = new $proxyName($this->getJsonRpcAdapter($expectedValue, $method, $params));
$this->assertSame($expectedValue, call_user_func_array(array($proxy, $method), $params));
}
/**
* @dataProvider getPropertyAccessProxies
*/
public function testJsonRpcPropertyReadAccess($instanceOrClassname, $publicProperty, $propertyValue)
{
$proxyName = $this->generateProxy($instanceOrClassname);
/* @var $proxy \ProxyManager\Proxy\RemoteObjectInterface */
$proxy = new $proxyName(
$this->getJsonRpcAdapter($propertyValue, '__get', array($publicProperty))
);
/* @var $proxy \ProxyManager\Proxy\NullObjectInterface */
$this->assertSame($propertyValue, $proxy->$publicProperty);
}
/**
* Generates a proxy for the given class name, and retrieves its class name
*
* @param string $parentClassName
*
* @return string
*/
private function generateProxy($parentClassName)
{
$generatedClassName = __NAMESPACE__ . '\\' . UniqueIdentifierGenerator::getIdentifier('Foo');
$generator = new RemoteObjectGenerator();
$generatedClass = new ClassGenerator($generatedClassName);
$strategy = new EvaluatingGeneratorStrategy();
$generator->generate(new ReflectionClass($parentClassName), $generatedClass);
$strategy->generate($generatedClass);
return $generatedClassName;
}
/**
* Generates a list of object | invoked method | parameters | expected result
*
* @return array
*/
public function getProxyMethods()
{
$selfHintParam = new ClassWithSelfHint();
$data = array(
array(
'ProxyManagerTestAsset\RemoteProxy\FooServiceInterface',
'foo',
array(),
'bar remote'
),
array(
'ProxyManagerTestAsset\RemoteProxy\Foo',
'foo',
array(),
'bar remote'
),
array(
new Foo(),
'foo',
array(),
'bar remote'
),
array(
'ProxyManagerTestAsset\RemoteProxy\BazServiceInterface',
'baz',
array('baz'),
'baz remote'
),
);
if (PHP_VERSION_ID >= 50401) {
// PHP < 5.4.1 misbehaves, throwing strict standards, see https://bugs.php.net/bug.php?id=60573
$data[] = array(
new ClassWithSelfHint(),
'selfHintMethod',
array($selfHintParam),
$selfHintParam
);
}
return $data;
}
/**
* Generates proxies and instances with a public property to feed to the property accessor methods
*
* @return array
*/
public function getPropertyAccessProxies()
{
return array(
array(
'ProxyManagerTestAsset\RemoteProxy\FooServiceInterface',
'publicProperty',
'publicProperty remote',
),
);
}
}

View File

@@ -1,65 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Generator;
use PHPUnit_Framework_TestCase;
use ProxyManager\Generator\ClassGenerator;
/**
* Tests for {@see \ProxyManager\Generator\ClassGenerator}
*
* @author Gordon Stratton <gordon.stratton@gmail.com>
* @license MIT
*
* @group Coverage
*/
class ClassGeneratorTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\Generator\ClassGenerator::setExtendedClass
*/
public function testExtendedClassesAreFQCNs()
{
$desiredFqcn = '\\stdClass';
$classNameInputs = array('stdClass', '\\stdClass\\');
foreach ($classNameInputs as $className) {
$classGenerator = new ClassGenerator();
$classGenerator->setExtendedClass($className);
$this->assertEquals($desiredFqcn, $classGenerator->getExtendedClass());
}
}
/**
* @covers \ProxyManager\Generator\ClassGenerator::setImplementedInterfaces
*/
public function testImplementedInterfacesAreFQCNs()
{
$desiredFqcns = array('\\Countable');
$interfaceNameInputs = array(array('Countable'), array('\\Countable\\'));
foreach ($interfaceNameInputs as $interfaceNames) {
$classGenerator = new ClassGenerator();
$classGenerator->setImplementedInterfaces($interfaceNames);
$this->assertEquals($desiredFqcns, $classGenerator->getImplementedInterfaces());
}
}
}

View File

@@ -1,56 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Generator;
use ReflectionClass;
use PHPUnit_Framework_TestCase;
use ProxyManager\Generator\MagicMethodGenerator;
/**
* Tests for {@see \ProxyManager\Generator\MagicMethodGenerator}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class MagicMethodGeneratorTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\Generator\MagicMethodGenerator::__construct
*/
public function testGeneratesCorrectByRefReturnValue()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\ClassWithByRefMagicMethods');
$magicMethod = new MagicMethodGenerator($reflection, '__get', array('name'));
$this->assertTrue($magicMethod->returnsReference());
}
/**
* @covers \ProxyManager\Generator\MagicMethodGenerator::__construct
*/
public function testGeneratesCorrectByValReturnValue()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\ClassWithMagicMethods');
$magicMethod = new MagicMethodGenerator($reflection, '__get', array('name'));
$this->assertFalse($magicMethod->returnsReference());
}
}

View File

@@ -1,97 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Generator;
use PHPUnit_Framework_TestCase;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\Generator\ParameterGenerator;
use Zend\Code\Reflection\MethodReflection;
/**
* Tests for {@see \ProxyManager\Generator\MethodGenerator}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\Generator\MethodGenerator
* @group Coverage
*/
class MethodGeneratorTest extends PHPUnit_Framework_TestCase
{
public function testGenerateSimpleMethod()
{
$methodGenerator = new MethodGenerator();
$methodGenerator->setReturnsReference(true);
$methodGenerator->setName('methodName');
$methodGenerator->setVisibility('protected');
$methodGenerator->setBody('/* body */');
$methodGenerator->setDocBlock('docBlock');
$methodGenerator->setParameter(new ParameterGenerator('foo'));
$this->assertSame(true, $methodGenerator->returnsReference());
$this->assertStringMatchesFormat(
'%a/**%adocBlock%a*/%aprotected function & methodName($foo)%a{%a/* body */%a}',
$methodGenerator->generate()
);
}
/**
* Verify that building from reflection works
*/
public function testGenerateFromReflection()
{
$method = MethodGenerator::fromReflection(new MethodReflection(__CLASS__, __FUNCTION__));
$this->assertSame(__FUNCTION__, $method->getName());
$this->assertSame(MethodGenerator::VISIBILITY_PUBLIC, $method->getVisibility());
$this->assertFalse($method->isStatic());
$this->assertSame('Verify that building from reflection works', $method->getDocBlock()->getShortDescription());
$method = MethodGenerator::fromReflection(
new MethodReflection('ProxyManagerTestAsset\\BaseClass', 'protectedMethod')
);
$this->assertSame(MethodGenerator::VISIBILITY_PROTECTED, $method->getVisibility());
$method = MethodGenerator::fromReflection(
new MethodReflection('ProxyManagerTestAsset\\BaseClass', 'privateMethod')
);
$this->assertSame(MethodGenerator::VISIBILITY_PRIVATE, $method->getVisibility());
}
public function testGeneratedParametersFromReflection()
{
$method = MethodGenerator::fromReflection(new MethodReflection(
'ProxyManagerTestAsset\\BaseClass',
'publicTypeHintedMethod'
));
$this->assertSame('publicTypeHintedMethod', $method->getName());
$parameters = $method->getParameters();
$this->assertCount(1, $parameters);
$param = $parameters['param'];
$this->assertSame('stdClass', $param->getType());
}
}

View File

@@ -1,146 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Generator;
use PHPUnit_Framework_TestCase;
use ProxyManager\Generator\ParameterGenerator;
use Zend\Code\Reflection\ParameterReflection;
/**
* Tests for {@see \ProxyManager\Generator\ParameterGenerator}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\Generator\ParameterGenerator
* @group Coverage
*/
class ParameterGeneratorTest extends PHPUnit_Framework_TestCase
{
public function testGeneratesProperTypeHint()
{
$generator = new ParameterGenerator('foo');
$generator->setType('array');
$this->assertSame('array $foo', $generator->generate());
$generator->setType('stdClass');
$this->assertSame('\\stdClass $foo', $generator->generate());
$generator->setType('\\fooClass');
$this->assertSame('\\fooClass $foo', $generator->generate());
}
public function testGeneratesMethodWithCallableType()
{
if (PHP_VERSION_ID < 50400) {
$this->markTestSkipped('`callable` is only supported in PHP >=5.4.0');
}
$generator = new ParameterGenerator();
$generator->setType('callable');
$generator->setName('foo');
$this->assertSame('callable $foo', $generator->generate());
}
public function testVisitMethodWithCallable()
{
if (PHP_VERSION_ID < 50400) {
$this->markTestSkipped('`callable` is only supported in PHP >=5.4.0');
}
$parameter = new ParameterReflection(
array('ProxyManagerTestAsset\\CallableTypeHintClass', 'callableTypeHintMethod'),
'parameter'
);
$generator = ParameterGenerator::fromReflection($parameter);
$this->assertSame('callable', $generator->getType());
}
public function testReadsParameterDefaults()
{
$parameter = ParameterGenerator::fromReflection(new ParameterReflection(
array(
'ProxyManagerTestAsset\\ClassWithMethodWithDefaultParameters',
'publicMethodWithDefaults'
),
'parameter'
));
/* @var $defaultValue \Zend\Code\Generator\ValueGenerator */
$defaultValue = $parameter->getDefaultValue();
$this->assertInstanceOf('Zend\\Code\\Generator\\ValueGenerator', $defaultValue);
$this->assertSame(array('foo'), $defaultValue->getValue());
$this->assertStringMatchesFormat('array%a$parameter%a=%aarray(\'foo\')', $parameter->generate());
}
public function testReadsParameterTypeHint()
{
$parameter = ParameterGenerator::fromReflection(new ParameterReflection(
array('ProxyManagerTestAsset\\BaseClass', 'publicTypeHintedMethod'),
'param'
));
$this->assertSame('stdClass', $parameter->getType());
}
public function testGeneratesParameterPassedByReference()
{
$parameter = new ParameterGenerator('foo');
$parameter->setPassedByReference(true);
$this->assertStringMatchesFormat('&%A$foo', $parameter->generate());
}
public function testGeneratesDefaultParameterForInternalPhpClasses()
{
$parameter = ParameterGenerator::fromReflection(new ParameterReflection(
array(
'Phar',
'compress'
),
1
));
$this->assertSame('null', strtolower((string) $parameter->getDefaultValue()));
}
public function testGeneratedParametersAreProperlyEscaped()
{
$parameter = new ParameterGenerator();
$parameter->setName('foo');
$parameter->setDefaultValue('\'bar\\baz');
$this->assertThat(
$parameter->generate(),
$this->logicalOr(
$this->equalTo('$foo = \'\\\'bar\\baz\''),
$this->equalTo('$foo = \'\\\'bar\\\\baz\'')
)
);
}
}

View File

@@ -1,72 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Generator\Util;
use ReflectionClass;
use PHPUnit_Framework_TestCase;
use ProxyManager\Generator\Util\ClassGeneratorUtils;
/**
* Test to {@see ProxyManager\Generator\Util\ClassGeneratorUtils}
*
* @author Jefersson Nathan <malukenho@phpse.net>
* @license MIT
*
* @covers ProxyManager\Generator\Util\ClassGeneratorUtils
*/
class ClassGeneratorUtilsTest extends PHPUnit_Framework_TestCase
{
public function testCantAddAFinalMethod()
{
$classGenerator = $this->getMock('Zend\\Code\\Generator\\ClassGenerator');
$methodGenerator = $this->getMock('Zend\\Code\\Generator\\MethodGenerator');
$methodGenerator
->expects($this->once())
->method('getName')
->willReturn('foo');
$classGenerator
->expects($this->never())
->method('addMethodFromGenerator');
$reflection = new ReflectionClass('ProxyManagerTestAsset\\ClassWithFinalMethods');
ClassGeneratorUtils::addMethodIfNotFinal($reflection, $classGenerator, $methodGenerator);
}
public function testCanAddANotFinalMethod()
{
$classGenerator = $this->getMock('Zend\\Code\\Generator\\ClassGenerator');
$methodGenerator = $this->getMock('Zend\\Code\\Generator\\MethodGenerator');
$methodGenerator
->expects($this->once())
->method('getName')
->willReturn('publicMethod');
$classGenerator
->expects($this->once())
->method('addMethodFromGenerator');
$reflection = new ReflectionClass('ProxyManagerTestAsset\\BaseClass');
ClassGeneratorUtils::addMethodIfNotFinal($reflection, $classGenerator, $methodGenerator);
}
}

View File

@@ -1,77 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Generator\Util;
use PHPUnit_Framework_TestCase;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
/**
* Tests for {@see \ProxyManager\Generator\Util\UniqueIdentifierGenerator}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class UniqueIdentifierGeneratorTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider getBaseIdentifierNames
*
* @covers \ProxyManager\Generator\Util\UniqueIdentifierGenerator::getIdentifier
*/
public function testGeneratesUniqueIdentifiers($name)
{
$this->assertNotSame(
UniqueIdentifierGenerator::getIdentifier($name),
UniqueIdentifierGenerator::getIdentifier($name)
);
}
/**
* @dataProvider getBaseIdentifierNames
*
* @covers \ProxyManager\Generator\Util\UniqueIdentifierGenerator::getIdentifier
*/
public function testGeneratesValidIdentifiers($name)
{
$this->assertRegExp(
'/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/',
UniqueIdentifierGenerator::getIdentifier($name)
);
}
/**
* Data provider generating identifier names to be checked
*
* @return string[][]
*/
public function getBaseIdentifierNames()
{
return array(
array(''),
array('1'),
array('foo'),
array('Foo'),
array('bar'),
array('Bar'),
array('foo_bar'),
);
}
}

View File

@@ -1,48 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\GeneratorStrategy;
use PHPUnit_Framework_TestCase;
use ProxyManager\GeneratorStrategy\BaseGeneratorStrategy;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
/**
* Tests for {@see \ProxyManager\GeneratorStrategy\BaseGeneratorStrategy}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class BaseGeneratorStrategyTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\GeneratorStrategy\BaseGeneratorStrategy::generate
*/
public function testGenerate()
{
$strategy = new BaseGeneratorStrategy();
$className = UniqueIdentifierGenerator::getIdentifier('Foo');
$classGenerator = new ClassGenerator($className);
$generated = $strategy->generate($classGenerator);
$this->assertGreaterThan(0, strpos($generated, $className));
}
}

View File

@@ -1,69 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\GeneratorStrategy;
use PHPUnit_Framework_TestCase;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
/**
* Tests for {@see \ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class EvaluatingGeneratorStrategyTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy::generate
* @covers \ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy::__construct
*/
public function testGenerate()
{
$strategy = new EvaluatingGeneratorStrategy();
$className = UniqueIdentifierGenerator::getIdentifier('Foo');
$classGenerator = new ClassGenerator($className);
$generated = $strategy->generate($classGenerator);
$this->assertGreaterThan(0, strpos($generated, $className));
$this->assertTrue(class_exists($className, false));
}
/**
* @covers \ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy::generate
* @covers \ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy::__construct
*/
public function testGenerateWithDisabledEval()
{
if (! ini_get('suhosin.executor.disable_eval')) {
$this->markTestSkipped('Ini setting "suhosin.executor.disable_eval" is needed to run this test');
}
$strategy = new EvaluatingGeneratorStrategy();
$className = 'Foo' . uniqid();
$classGenerator = new ClassGenerator($className);
$generated = $strategy->generate($classGenerator);
$this->assertGreaterThan(0, strpos($generated, $className));
$this->assertTrue(class_exists($className, false));
}
}

View File

@@ -1,148 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\GeneratorStrategy;
use PHPUnit_Framework_TestCase;
use ProxyManager\Exception\FileNotWritableException;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use ProxyManager\GeneratorStrategy\FileWriterGeneratorStrategy;
/**
* Tests for {@see \ProxyManager\GeneratorStrategy\FileWriterGeneratorStrategy}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*
* Note: this test generates temporary files that are not deleted
*/
class FileWriterGeneratorStrategyTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\GeneratorStrategy\FileWriterGeneratorStrategy::__construct
* @covers \ProxyManager\GeneratorStrategy\FileWriterGeneratorStrategy::generate
*/
public function testGenerate()
{
/* @var $locator \ProxyManager\FileLocator\FileLocatorInterface|\PHPUnit_Framework_MockObject_MockObject */
$locator = $this->getMock('ProxyManager\\FileLocator\\FileLocatorInterface');
$generator = new FileWriterGeneratorStrategy($locator);
$tmpFile = sys_get_temp_dir() . '/' . uniqid('FileWriterGeneratorStrategyTest', true) . '.php';
$namespace = 'Foo';
$className = UniqueIdentifierGenerator::getIdentifier('Bar');
$fqcn = $namespace . '\\' . $className;
$locator
->expects($this->any())
->method('getProxyFileName')
->with($fqcn)
->will($this->returnValue($tmpFile));
$body = $generator->generate(new ClassGenerator($fqcn));
$this->assertGreaterThan(0, strpos($body, $className));
$this->assertFalse(class_exists($fqcn, false));
$this->assertTrue(file_exists($tmpFile));
require $tmpFile;
$this->assertTrue(class_exists($fqcn, false));
}
public function testGenerateWillFailIfTmpFileCannotBeWrittenToDisk()
{
$tmpDirPath = sys_get_temp_dir() . '/' . uniqid('nonWritable', true);
mkdir($tmpDirPath, 0555, true);
/* @var $locator \ProxyManager\FileLocator\FileLocatorInterface|\PHPUnit_Framework_MockObject_MockObject */
$locator = $this->getMock('ProxyManager\\FileLocator\\FileLocatorInterface');
$generator = new FileWriterGeneratorStrategy($locator);
$tmpFile = $tmpDirPath . '/' . uniqid('FileWriterGeneratorStrategyFailedFileWriteTest', true) . '.php';
$namespace = 'Foo';
$className = UniqueIdentifierGenerator::getIdentifier('Bar');
$fqcn = $namespace . '\\' . $className;
$locator
->expects($this->any())
->method('getProxyFileName')
->with($fqcn)
->will($this->returnValue($tmpFile));
$this->setExpectedException('ProxyManager\\Exception\\FileNotWritableException');
$generator->generate(new ClassGenerator($fqcn));
}
public function testGenerateWillFailIfTmpFileCannotBeMovedToFinalDestination()
{
/* @var $locator \ProxyManager\FileLocator\FileLocatorInterface|\PHPUnit_Framework_MockObject_MockObject */
$locator = $this->getMock('ProxyManager\\FileLocator\\FileLocatorInterface');
$generator = new FileWriterGeneratorStrategy($locator);
$tmpFile = sys_get_temp_dir() . '/' . uniqid('FileWriterGeneratorStrategyFailedFileMoveTest', true) . '.php';
$namespace = 'Foo';
$className = UniqueIdentifierGenerator::getIdentifier('Bar');
$fqcn = $namespace . '\\' . $className;
$locator
->expects($this->any())
->method('getProxyFileName')
->with($fqcn)
->will($this->returnValue($tmpFile));
mkdir($tmpFile);
$this->setExpectedException('ProxyManager\\Exception\\FileNotWritableException');
$generator->generate(new ClassGenerator($fqcn));
}
public function testWhenFailingAllTemporaryFilesAreRemoved()
{
$tmpDirPath = sys_get_temp_dir() . '/' . uniqid('noTempFilesLeftBehind', true);
mkdir($tmpDirPath);
/* @var $locator \ProxyManager\FileLocator\FileLocatorInterface|\PHPUnit_Framework_MockObject_MockObject */
$locator = $this->getMock('ProxyManager\\FileLocator\\FileLocatorInterface');
$generator = new FileWriterGeneratorStrategy($locator);
$tmpFile = $tmpDirPath . '/' . uniqid('FileWriterGeneratorStrategyFailedFileMoveTest', true) . '.php';
$namespace = 'Foo';
$className = UniqueIdentifierGenerator::getIdentifier('Bar');
$fqcn = $namespace . '\\' . $className;
$locator
->expects($this->any())
->method('getProxyFileName')
->with($fqcn)
->will($this->returnValue($tmpFile));
mkdir($tmpFile);
try {
$generator->generate(new ClassGenerator($fqcn));
$this->fail('An exception was supposed to be thrown');
} catch (FileNotWritableException $exception) {
rmdir($tmpFile);
$this->assertEquals(array('.', '..'), scandir($tmpDirPath));
}
}
}

View File

@@ -1,161 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Inflector;
use PHPUnit_Framework_TestCase;
use ProxyManager\Inflector\ClassNameInflector;
use ProxyManager\Inflector\ClassNameInflectorInterface;
/**
* Tests for {@see \ProxyManager\Inflector\ClassNameInflector}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class ClassNameInflectorTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider getClassNames
*
* @covers \ProxyManager\Inflector\ClassNameInflector::__construct
* @covers \ProxyManager\Inflector\ClassNameInflector::getUserClassName
* @covers \ProxyManager\Inflector\ClassNameInflector::getProxyClassName
* @covers \ProxyManager\Inflector\ClassNameInflector::isProxyClassName
*/
public function testInflector($realClassName, $proxyClassName)
{
$inflector = new ClassNameInflector('ProxyNS');
$this->assertFalse($inflector->isProxyClassName($realClassName));
$this->assertTrue($inflector->isProxyClassName($proxyClassName));
$this->assertStringMatchesFormat($realClassName, $inflector->getUserClassName($realClassName));
$this->assertStringMatchesFormat($proxyClassName, $inflector->getProxyClassName($proxyClassName));
$this->assertStringMatchesFormat($proxyClassName, $inflector->getProxyClassName($realClassName));
$this->assertStringMatchesFormat($realClassName, $inflector->getUserClassName($proxyClassName));
}
/**
* @covers \ProxyManager\Inflector\ClassNameInflector::getProxyClassName
*/
public function testGeneratesSameClassNameWithSameParameters()
{
$inflector = new ClassNameInflector('ProxyNS');
$this->assertSame($inflector->getProxyClassName('Foo\\Bar'), $inflector->getProxyClassName('Foo\\Bar'));
$this->assertSame(
$inflector->getProxyClassName('Foo\\Bar', array('baz' => 'tab')),
$inflector->getProxyClassName('Foo\\Bar', array('baz' => 'tab'))
);
$this->assertSame(
$inflector->getProxyClassName('Foo\\Bar', array('tab' => 'baz')),
$inflector->getProxyClassName('Foo\\Bar', array('tab' => 'baz'))
);
}
/**
* @covers \ProxyManager\Inflector\ClassNameInflector::getProxyClassName
*/
public function testGeneratesDifferentClassNameWithDifferentParameters()
{
$inflector = new ClassNameInflector('ProxyNS');
$this->assertNotSame(
$inflector->getProxyClassName('Foo\\Bar'),
$inflector->getProxyClassName('Foo\\Bar', array('foo' => 'bar'))
);
$this->assertNotSame(
$inflector->getProxyClassName('Foo\\Bar', array('baz' => 'tab')),
$inflector->getProxyClassName('Foo\\Bar', array('tab' => 'baz'))
);
$this->assertNotSame(
$inflector->getProxyClassName('Foo\\Bar', array('foo' => 'bar', 'tab' => 'baz')),
$inflector->getProxyClassName('Foo\\Bar', array('foo' => 'bar'))
);
$this->assertNotSame(
$inflector->getProxyClassName('Foo\\Bar', array('foo' => 'bar', 'tab' => 'baz')),
$inflector->getProxyClassName('Foo\\Bar', array('tab' => 'baz', 'foo' => 'bar'))
);
}
/**
* @covers \ProxyManager\Inflector\ClassNameInflector::getProxyClassName
*/
public function testGeneratesCorrectClassNameWhenGivenLeadingBackslash()
{
$inflector = new ClassNameInflector('ProxyNS');
$this->assertSame(
$inflector->getProxyClassName('\\Foo\\Bar', array('tab' => 'baz')),
$inflector->getProxyClassName('Foo\\Bar', array('tab' => 'baz'))
);
}
/**
* @covers \ProxyManager\Inflector\ClassNameInflector::getProxyClassName
*
* @dataProvider getClassAndParametersCombinations
*
* @param string $className
* @param array $parameters
*/
public function testClassNameIsValidClassIdentifier($className, array $parameters)
{
$inflector = new ClassNameInflector('ProxyNS');
$this->assertRegExp(
'/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+)(\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+)*/',
$inflector->getProxyClassName($className, $parameters),
'Class name string is a valid class identifier'
);
}
/**
* Data provider.
*
* @return array[]
*/
public function getClassNames()
{
return array(
array('Foo', 'ProxyNS\\' . ClassNameInflectorInterface::PROXY_MARKER . '\\Foo\\%s'),
array('Foo\\Bar', 'ProxyNS\\' . ClassNameInflectorInterface::PROXY_MARKER . '\\Foo\\Bar\\%s'),
);
}
/**
* Data provider.
*
* @return array[]
*/
public function getClassAndParametersCombinations()
{
return array(
array('Foo', array()),
array('Foo\\Bar', array()),
array('Foo', array(null)),
array('Foo\\Bar', array(null)),
array('Foo', array('foo' => 'bar')),
array('Foo\\Bar', array('foo' => 'bar')),
array('Foo', array("\0" => "very \0 bad")),
array('Foo\\Bar', array("\0" => "very \0 bad")),
);
}
}

View File

@@ -1,66 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Inflector\Util;
use PHPUnit_Framework_TestCase;
use ProxyManager\Inflector\Util\ParameterEncoder;
/**
* Tests for {@see \ProxyManager\Inflector\Util\ParameterEncoder}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class ParameterEncoderTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider getParameters
*
* @covers \ProxyManager\Inflector\Util\ParameterEncoder::encodeParameters
*/
public function testGeneratesValidClassName(array $parameters)
{
$encoder = new ParameterEncoder();
$this->assertRegExp(
'/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+/',
$encoder->encodeParameters($parameters),
'Encoded string is a valid class identifier'
);
}
/**
* @return array
*/
public function getParameters()
{
return array(
array(array()),
array(array('foo' => 'bar')),
array(array('bar' => 'baz')),
array(array(null)),
array(array(null, null)),
array(array('bar' => null)),
array(array('bar' => 12345)),
array(array('foo' => 'bar', 'bar' => 'baz')),
);
}
}

View File

@@ -1,62 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\Inflector\Util;
use PHPUnit_Framework_TestCase;
use ProxyManager\Inflector\Util\ParameterHasher;
/**
* Tests for {@see \ProxyManager\Inflector\Util\ParameterHasher}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class ParameterHasherTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider getParameters
*
* @covers \ProxyManager\Inflector\Util\ParameterHasher::hashParameters
*/
public function testGeneratesValidClassName(array $parameters, $expectedHash)
{
$encoder = new ParameterHasher();
$this->assertSame($expectedHash, $encoder->hashParameters($parameters));
}
/**
* @return array
*/
public function getParameters()
{
return array(
array(array(), '40cd750bba9870f18aada2478b24840a'),
array(array('foo' => 'bar'), '49a3696adf0fbfacc12383a2d7400d51'),
array(array('bar' => 'baz'), '6ed41c8a63c1571554ecaeb998198757'),
array(array(null), '38017a839aaeb8ff1a658fce9af6edd3'),
array(array(null, null), '12051f9a58288e5328ad748881cc4e00'),
array(array('bar' => null), '0dbb112e1c4e6e4126232de2daa2d660'),
array(array('bar' => 12345), 'eb6291ea4973741bf9b6571f49b4ffd2'),
array(array('foo' => 'bar', 'bar' => 'baz'), '4447ff857f244d24c31bd84d7a855eda'),
);
}
}

View File

@@ -1,95 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator;
use PHPUnit_Framework_TestCase;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ReflectionClass;
/**
* Base test for proxy generators
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
abstract class AbstractProxyGeneratorTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider getTestedImplementations
*
* Verifies that generated code is valid and implements expected interfaces
*/
public function testGeneratesValidCode($className)
{
$generator = $this->getProxyGenerator();
$generatedClassName = UniqueIdentifierGenerator::getIdentifier('AbstractProxyGeneratorTest');
$generatedClass = new ClassGenerator($generatedClassName);
$originalClass = new ReflectionClass($className);
$generatorStrategy = new EvaluatingGeneratorStrategy();
$generator->generate($originalClass, $generatedClass);
$generatorStrategy->generate($generatedClass);
$generatedReflection = new ReflectionClass($generatedClassName);
if ($originalClass->isInterface()) {
$this->assertTrue($generatedReflection->implementsInterface($className));
} else {
$this->assertSame($originalClass->getName(), $generatedReflection->getParentClass()->getName());
}
$this->assertSame($generatedClassName, $generatedReflection->getName());
foreach ($this->getExpectedImplementedInterfaces() as $interface) {
$this->assertTrue($generatedReflection->implementsInterface($interface));
}
}
/**
* Retrieve a new generator instance
*
* @return \ProxyManager\ProxyGenerator\ProxyGeneratorInterface
*/
abstract protected function getProxyGenerator();
/**
* Retrieve interfaces that should be implemented by the generated code
*
* @return string[]
*/
abstract protected function getExpectedImplementedInterfaces();
/**
* @return array
*/
public function getTestedImplementations()
{
return array(
array('ProxyManagerTestAsset\\BaseClass'),
array('ProxyManagerTestAsset\\ClassWithMagicMethods'),
array('ProxyManagerTestAsset\\ClassWithByRefMagicMethods'),
array('ProxyManagerTestAsset\\ClassWithMixedProperties'),
array('ProxyManagerTestAsset\\BaseInterface'),
);
}
}

View File

@@ -1,62 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptor\MethodGenerator;
use ReflectionClass;
use PHPUnit_Framework_TestCase;
use ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\MagicWakeup;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\MagicWakeup}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class MagicWakeupTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\MagicWakeup::__construct
*/
public function testBodyStructure()
{
$reflection = new ReflectionClass(
'ProxyManagerTestAsset\\ProxyGenerator\\LazyLoading\\MethodGenerator\\ClassWithTwoPublicProperties'
);
$magicWakeup = new MagicWakeup($reflection);
$this->assertSame('__wakeup', $magicWakeup->getName());
$this->assertCount(0, $magicWakeup->getParameters());
$this->assertSame("unset(\$this->bar, \$this->baz);", $magicWakeup->getBody());
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\MagicWakeup::__construct
*/
public function testBodyStructureWithoutPublicProperties()
{
$magicWakeup = new MagicWakeup(new ReflectionClass('ProxyManagerTestAsset\\EmptyClass'));
$this->assertSame('__wakeup', $magicWakeup->getName());
$this->assertCount(0, $magicWakeup->getParameters());
$this->assertEmpty($magicWakeup->getBody());
}
}

View File

@@ -1,49 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptor\MethodGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\SetMethodPrefixInterceptor;
use PHPUnit_Framework_TestCase;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\SetMethodPrefixInterceptor}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class SetMethodPrefixInterceptorTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\SetMethodPrefixInterceptor::__construct
*/
public function testBodyStructure()
{
$suffix = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffix->expects($this->once())->method('getName')->will($this->returnValue('foo'));
$setter = new SetMethodPrefixInterceptor($suffix);
$this->assertSame('setMethodPrefixInterceptor', $setter->getName());
$this->assertCount(2, $setter->getParameters());
$this->assertSame('$this->foo[$methodName] = $prefixInterceptor;', $setter->getBody());
}
}

View File

@@ -1,49 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptor\MethodGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\SetMethodSuffixInterceptor;
use PHPUnit_Framework_TestCase;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\SetMethodSuffixInterceptor}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class SetMethodSuffixInterceptorTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\SetMethodSuffixInterceptor::__construct
*/
public function testBodyStructure()
{
$suffix = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffix->expects($this->once())->method('getName')->will($this->returnValue('foo'));
$setter = new SetMethodSuffixInterceptor($suffix);
$this->assertSame('setMethodSuffixInterceptor', $setter->getName());
$this->assertCount(2, $setter->getParameters());
$this->assertSame('$this->foo[$methodName] = $suffixInterceptor;', $setter->getBody());
}
}

View File

@@ -1,42 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptor\PropertyGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator\MethodPrefixInterceptors;
use ProxyManagerTest\ProxyGenerator\PropertyGenerator\AbstractUniquePropertyNameTest;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator\MethodPrefixInterceptors}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator\MethodPrefixInterceptors
* @group Coverage
*/
class MethodPrefixInterceptorsTest extends AbstractUniquePropertyNameTest
{
/**
* {@inheritDoc}
*/
protected function createProperty()
{
return new MethodPrefixInterceptors();
}
}

View File

@@ -1,42 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptor\PropertyGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator\MethodSuffixInterceptors;
use ProxyManagerTest\ProxyGenerator\PropertyGenerator\AbstractUniquePropertyNameTest;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator\MethodSuffixInterceptors}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator\MethodSuffixInterceptors
* @group Coverage
*/
class MethodSuffixInterceptorsTest extends AbstractUniquePropertyNameTest
{
/**
* {@inheritDoc}
*/
protected function createProperty()
{
return new MethodSuffixInterceptors();
}
}

View File

@@ -1,207 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use PHPUnit_Framework_TestCase;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Constructor;
use ReflectionClass;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Constructor}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class ConstructorTest extends PHPUnit_Framework_TestCase
{
private $prefixInterceptors;
private $suffixInterceptors;
public function setUp()
{
$this->prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$this->suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$this->prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$this->suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Constructor::__construct
*/
public function testSignature()
{
$constructor = new Constructor(
new ReflectionClass('ProxyManagerTestAsset\\ClassWithProtectedProperties'),
$this->prefixInterceptors,
$this->suffixInterceptors
);
$this->assertSame('__construct', $constructor->getName());
$parameters = $constructor->getParameters();
$this->assertCount(3, $parameters);
$this->assertSame(
'ProxyManagerTestAsset\\ClassWithProtectedProperties',
$parameters['localizedObject']->getType()
);
$this->assertSame('array', $parameters['prefixInterceptors']->getType());
$this->assertSame('array', $parameters['suffixInterceptors']->getType());
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Constructor::__construct
*/
public function testBodyStructure()
{
$constructor = new Constructor(
new ReflectionClass('ProxyManagerTestAsset\\ClassWithPublicProperties'),
$this->prefixInterceptors,
$this->suffixInterceptors
);
$this->assertSame(
'$this->property0 = & $localizedObject->property0;
$this->property1 = & $localizedObject->property1;
$this->property2 = & $localizedObject->property2;
$this->property3 = & $localizedObject->property3;
$this->property4 = & $localizedObject->property4;
$this->property5 = & $localizedObject->property5;
$this->property6 = & $localizedObject->property6;
$this->property7 = & $localizedObject->property7;
$this->property8 = & $localizedObject->property8;
$this->property9 = & $localizedObject->property9;
$this->pre = $prefixInterceptors;
$this->post = $suffixInterceptors;',
$constructor->getBody()
);
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Constructor::__construct
*/
public function testBodyStructureWithProtectedProperties()
{
$constructor = new Constructor(
new ReflectionClass('ProxyManagerTestAsset\\ClassWithProtectedProperties'),
$this->prefixInterceptors,
$this->suffixInterceptors
);
$this->assertSame(
'$this->property0 = & $localizedObject->property0;
$this->property1 = & $localizedObject->property1;
$this->property2 = & $localizedObject->property2;
$this->property3 = & $localizedObject->property3;
$this->property4 = & $localizedObject->property4;
$this->property5 = & $localizedObject->property5;
$this->property6 = & $localizedObject->property6;
$this->property7 = & $localizedObject->property7;
$this->property8 = & $localizedObject->property8;
$this->property9 = & $localizedObject->property9;
$this->pre = $prefixInterceptors;
$this->post = $suffixInterceptors;',
$constructor->getBody()
);
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Constructor::__construct
*/
public function testBodyStructureWithPrivateProperties()
{
if (! method_exists('Closure', 'bind')) {
$this->setExpectedException('ProxyManager\Exception\UnsupportedProxiedClassException');
}
$constructor = new Constructor(
new ReflectionClass('ProxyManagerTestAsset\\ClassWithPrivateProperties'),
$this->prefixInterceptors,
$this->suffixInterceptors
);
$this->assertSame(
'\Closure::bind(function () use ($localizedObject) {
$this->property0 = & $localizedObject->property0;
}, $this, \'ProxyManagerTestAsset\\\\ClassWithPrivateProperties\')->__invoke();
\Closure::bind(function () use ($localizedObject) {
$this->property1 = & $localizedObject->property1;
}, $this, \'ProxyManagerTestAsset\\\\ClassWithPrivateProperties\')->__invoke();
\Closure::bind(function () use ($localizedObject) {
$this->property2 = & $localizedObject->property2;
}, $this, \'ProxyManagerTestAsset\\\\ClassWithPrivateProperties\')->__invoke();
\Closure::bind(function () use ($localizedObject) {
$this->property3 = & $localizedObject->property3;
}, $this, \'ProxyManagerTestAsset\\\\ClassWithPrivateProperties\')->__invoke();
\Closure::bind(function () use ($localizedObject) {
$this->property4 = & $localizedObject->property4;
}, $this, \'ProxyManagerTestAsset\\\\ClassWithPrivateProperties\')->__invoke();
\Closure::bind(function () use ($localizedObject) {
$this->property5 = & $localizedObject->property5;
}, $this, \'ProxyManagerTestAsset\\\\ClassWithPrivateProperties\')->__invoke();
\Closure::bind(function () use ($localizedObject) {
$this->property6 = & $localizedObject->property6;
}, $this, \'ProxyManagerTestAsset\\\\ClassWithPrivateProperties\')->__invoke();
\Closure::bind(function () use ($localizedObject) {
$this->property7 = & $localizedObject->property7;
}, $this, \'ProxyManagerTestAsset\\\\ClassWithPrivateProperties\')->__invoke();
\Closure::bind(function () use ($localizedObject) {
$this->property8 = & $localizedObject->property8;
}, $this, \'ProxyManagerTestAsset\\\\ClassWithPrivateProperties\')->__invoke();
\Closure::bind(function () use ($localizedObject) {
$this->property9 = & $localizedObject->property9;
}, $this, \'ProxyManagerTestAsset\\\\ClassWithPrivateProperties\')->__invoke();
$this->pre = $prefixInterceptors;
$this->post = $suffixInterceptors;',
$constructor->getBody()
);
}
}

View File

@@ -1,62 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use PHPUnit_Framework_TestCase;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\InterceptedMethod;
use Zend\Code\Reflection\MethodReflection;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\InterceptedMethod}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\InterceptedMethod
* @group Coverage
*/
class InterceptedMethodTest extends PHPUnit_Framework_TestCase
{
public function testBodyStructure()
{
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$method = InterceptedMethod::generateMethod(
new MethodReflection('ProxyManagerTestAsset\\BaseClass', 'publicByReferenceParameterMethod'),
$prefixInterceptors,
$suffixInterceptors
);
$this->assertInstanceOf('ProxyManager\\Generator\\MethodGenerator', $method);
$this->assertSame('publicByReferenceParameterMethod', $method->getName());
$this->assertCount(2, $method->getParameters());
$this->assertGreaterThan(
0,
strpos(
$method->getBody(),
'$returnValue = parent::publicByReferenceParameterMethod($param, $byRefParam);'
)
);
}
}

View File

@@ -1,72 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ReflectionClass;
use PHPUnit_Framework_TestCase;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicClone;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicClone}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class MagicCloneTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicClone::__construct
*/
public function testBodyStructure()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\EmptyClass');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicClone = new MagicClone($reflection, $prefixInterceptors, $suffixInterceptors);
$this->assertSame('__clone', $magicClone->getName());
$this->assertCount(0, $magicClone->getParameters());
$this->assertStringMatchesFormat("%a\n\n\$returnValue = null;\n\n%a", $magicClone->getBody());
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicClone::__construct
*/
public function testBodyStructureWithInheritedMethod()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\ClassWithMagicMethods');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicClone = new MagicClone($reflection, $prefixInterceptors, $suffixInterceptors);
$this->assertSame('__clone', $magicClone->getName());
$this->assertCount(0, $magicClone->getParameters());
$this->assertStringMatchesFormat("%a\n\n\$returnValue = parent::__clone();\n\n%a", $magicClone->getBody());
}
}

View File

@@ -1,80 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ReflectionClass;
use PHPUnit_Framework_TestCase;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicGet;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicGet}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class MagicGetTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicGet::__construct
*/
public function testBodyStructure()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\EmptyClass');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicGet = new MagicGet(
$reflection,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame('__get', $magicGet->getName());
$this->assertCount(1, $magicGet->getParameters());
$this->assertStringMatchesFormat('%a$returnValue = & $accessor();%a', $magicGet->getBody());
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicGet::__construct
*/
public function testBodyStructureWithInheritedMethod()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\ClassWithMagicMethods');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicGet = new MagicGet(
$reflection,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame('__get', $magicGet->getName());
$this->assertCount(1, $magicGet->getParameters());
$this->assertStringMatchesFormat('%a$returnValue = & parent::__get($name);%a', $magicGet->getBody());
}
}

View File

@@ -1,80 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ReflectionClass;
use PHPUnit_Framework_TestCase;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicIsset;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicIsset}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class MagicIssetTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicIsset::__construct
*/
public function testBodyStructure()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\EmptyClass');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicGet = new MagicIsset(
$reflection,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame('__isset', $magicGet->getName());
$this->assertCount(1, $magicGet->getParameters());
$this->assertStringMatchesFormat('%a$returnValue = $accessor();%a', $magicGet->getBody());
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicIsset::__construct
*/
public function testBodyStructureWithInheritedMethod()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\ClassWithMagicMethods');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicGet = new MagicIsset(
$reflection,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame('__isset', $magicGet->getName());
$this->assertCount(1, $magicGet->getParameters());
$this->assertStringMatchesFormat('%a$returnValue = & parent::__isset($name);%a', $magicGet->getBody());
}
}

View File

@@ -1,80 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ReflectionClass;
use PHPUnit_Framework_TestCase;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicSet;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicSet}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class MagicSetTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicSet::__construct
*/
public function testBodyStructure()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\EmptyClass');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicGet = new MagicSet(
$reflection,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame('__set', $magicGet->getName());
$this->assertCount(2, $magicGet->getParameters());
$this->assertStringMatchesFormat('%a$returnValue = & $accessor();%a', $magicGet->getBody());
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicSet::__construct
*/
public function testBodyStructureWithInheritedMethod()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\ClassWithMagicMethods');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicGet = new MagicSet(
$reflection,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame('__set', $magicGet->getName());
$this->assertCount(2, $magicGet->getParameters());
$this->assertStringMatchesFormat('%a$returnValue = & parent::__set($name, $value);%a', $magicGet->getBody());
}
}

View File

@@ -1,80 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ReflectionClass;
use PHPUnit_Framework_TestCase;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicSleep;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicSleep}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class MagicSleepTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicSleep::__construct
*/
public function testBodyStructure()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\EmptyClass');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicGet = new MagicSleep(
$reflection,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame('__sleep', $magicGet->getName());
$this->assertEmpty($magicGet->getParameters());
$this->assertStringMatchesFormat('%a$returnValue = array_keys((array) $this);%a', $magicGet->getBody());
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicSleep::__construct
*/
public function testBodyStructureWithInheritedMethod()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\ClassWithMagicMethods');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicGet = new MagicSleep(
$reflection,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame('__sleep', $magicGet->getName());
$this->assertEmpty($magicGet->getParameters());
$this->assertStringMatchesFormat('%a$returnValue = & parent::__sleep();%a', $magicGet->getBody());
}
}

View File

@@ -1,80 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ReflectionClass;
use PHPUnit_Framework_TestCase;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicUnset;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicUnset}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class MagicUnsetTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicUnset::__construct
*/
public function testBodyStructure()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\EmptyClass');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicGet = new MagicUnset(
$reflection,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame('__unset', $magicGet->getName());
$this->assertCount(1, $magicGet->getParameters());
$this->assertStringMatchesFormat('%a$returnValue = $accessor();%a', $magicGet->getBody());
}
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicUnset::__construct
*/
public function testBodyStructureWithInheritedMethod()
{
$reflection = new ReflectionClass('ProxyManagerTestAsset\\ClassWithMagicMethods');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$magicGet = new MagicUnset(
$reflection,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame('__unset', $magicGet->getName());
$this->assertCount(1, $magicGet->getParameters());
$this->assertStringMatchesFormat('%a$returnValue = & parent::__unset($name);%a', $magicGet->getBody());
}
}

View File

@@ -1,81 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util;
use PHPUnit_Framework_TestCase;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util\InterceptorGenerator;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorValueHolderGenerator}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @group Coverage
*/
class InterceptorGeneratorTest extends PHPUnit_Framework_TestCase
{
/**
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util\InterceptorGenerator
*/
public function testInterceptorGenerator()
{
$method = $this->getMock('ProxyManager\\Generator\\MethodGenerator');
$bar = $this->getMock('ProxyManager\\Generator\\ParameterGenerator');
$baz = $this->getMock('ProxyManager\\Generator\\ParameterGenerator');
$prefixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$suffixInterceptors = $this->getMock('Zend\\Code\\Generator\\PropertyGenerator');
$bar->expects($this->any())->method('getName')->will($this->returnValue('bar'));
$baz->expects($this->any())->method('getName')->will($this->returnValue('baz'));
$method->expects($this->any())->method('getName')->will($this->returnValue('fooMethod'));
$method->expects($this->any())->method('getParameters')->will($this->returnValue(array($bar, $baz)));
$prefixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('pre'));
$suffixInterceptors->expects($this->any())->method('getName')->will($this->returnValue('post'));
$body = InterceptorGenerator::createInterceptedMethodBody(
'$returnValue = "foo";',
$method,
$prefixInterceptors,
$suffixInterceptors
);
$this->assertSame(
'if (isset($this->pre[\'fooMethod\'])) {' . "\n"
. ' $returnEarly = false;' . "\n"
. ' $prefixReturnValue = $this->pre[\'fooMethod\']->__invoke($this, $this, \'fooMethod\', '
. 'array(\'bar\' => $bar, \'baz\' => $baz), $returnEarly);' . "\n\n"
. ' if ($returnEarly) {' . "\n"
. ' return $prefixReturnValue;' . "\n"
. ' }' . "\n"
. '}' . "\n\n"
. '$returnValue = "foo";' . "\n\n"
. 'if (isset($this->post[\'fooMethod\'])) {' . "\n"
. ' $returnEarly = false;' . "\n"
. ' $suffixReturnValue = $this->post[\'fooMethod\']->__invoke($this, $this, \'fooMethod\', '
. 'array(\'bar\' => $bar, \'baz\' => $baz), $returnValue, $returnEarly);' . "\n\n"
. ' if ($returnEarly) {' . "\n"
. ' return $suffixReturnValue;' . "\n"
. ' }' . "\n"
. '}' . "\n\n"
. 'return $returnValue;',
$body
);
}
}

View File

@@ -1,76 +0,0 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace ProxyManagerTest\ProxyGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizerGenerator;
use ReflectionClass;
use ReflectionProperty;
/**
* Tests for {@see \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizerGenerator}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @covers \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizerGenerator
* @group Coverage
*/
class AccessInterceptorScopeLocalizerTest extends AbstractProxyGeneratorTest
{
/**
* @dataProvider getTestedImplementations
*
* {@inheritDoc}
*/
public function testGeneratesValidCode($className)
{
$reflectionClass = new ReflectionClass($className);
if ($reflectionClass->isInterface()) {
// @todo interfaces *may* be proxied by deferring property localization to the constructor (no hardcoding)
$this->setExpectedException('ProxyManager\Exception\InvalidProxiedClassException');
return parent::testGeneratesValidCode($className);
}
if ((! method_exists('Closure', 'bind'))
&& $reflectionClass->getProperties(ReflectionProperty::IS_PRIVATE)
) {
$this->setExpectedException('ProxyManager\Exception\UnsupportedProxiedClassException');
}
return parent::testGeneratesValidCode($className);
}
/**
* {@inheritDoc}
*/
protected function getProxyGenerator()
{
return new AccessInterceptorScopeLocalizerGenerator();
}
/**
* {@inheritDoc}
*/
protected function getExpectedImplementedInterfaces()
{
return array('ProxyManager\\Proxy\\AccessInterceptorInterface');
}
}

Some files were not shown because too many files have changed in this diff Show More