Actualización

This commit is contained in:
Xes
2025-04-10 12:24:57 +02:00
parent 8969cc929d
commit 45420b6f0d
39760 changed files with 4303286 additions and 0 deletions

View File

@@ -0,0 +1,339 @@
---
title: Changelog
---
This is a list of changes/improvements that were introduced in ProxyManager
## 2.0.4
### Fixed
- Remove deprecated `getMock` usage from tests [#325](https://github.com/Ocramius/ProxyManager/pull/325)
- Fix incorrect type in docs example [#329](https://github.com/Ocramius/ProxyManager/pull/329)
- Bug when proxy `__get` magic method [#344](https://github.com/Ocramius/ProxyManager/pull/344)
- Fix lazy loading value holder magic method support [#345](https://github.com/Ocramius/ProxyManager/pull/345)
## 2.0.3
### Fixed
- Various test suite cleanups, mostly because of
[new PHPUnit 5.4.0 deprecations being introduced](https://github.com/sebastianbergmann/phpunit/wiki/Release-Announcement-for-PHPUnit-5.4.0)
[#318](https://github.com/Ocramius/ProxyManager/issues/318)
- Removed `zendframework/zend-code:3.0.3` from installable dependencies, since
a critical bug was introduced in it [#321](https://github.com/Ocramius/ProxyManager/issues/321)
[#323](https://github.com/Ocramius/ProxyManager/issues/323)
[#324](https://github.com/Ocramius/ProxyManager/issues/324). Please upgrade to
`zendframework/zend-code:3.0.4` or newer.
## 2.0.2
### Fixed
- Various optimizations were performed in the [`ocramius/package-versions`](https://github.com/Ocramius/PackageVersions)
integration in order to prevent "class not found" fatals. [#294](https://github.com/Ocramius/ProxyManager/issues/294)
- Null objects produced via a given class name were not extending from the given class name, causing obvious LSP
compliance and type-compatibility issues. [#300](https://github.com/Ocramius/ProxyManager/issues/300)
[#301](https://github.com/Ocramius/ProxyManager/issues/301)
- Specific installation versions were removed from the [README.md](README.md) install instructions, since composer
is installing the latest available version by default. [#305](https://github.com/Ocramius/ProxyManager/issues/305)
- PHP 7.0.6 support was dropped. PHP 7.0.6 includes some nasty reflection bugs that caused `__isset` to be called when
`ReflectionProperty#getValue()` is used (https://bugs.php.net/72174).
[#306](https://github.com/Ocramius/ProxyManager/issues/306)
[#308](https://github.com/Ocramius/ProxyManager/issues/308)
- PHP 7.0.7 contains additional limitations as to when `$this` can be used. Specifically, `$this` cannot be used as a
parameter name for closures that have an already assigned `$this`. Due to `$this` being incorrectly used as parameter
name within this library, running ProxyManager on PHP 7.0.7 would have caused a fatal error.
[#306](https://github.com/Ocramius/ProxyManager/issues/306)
[#308](https://github.com/Ocramius/ProxyManager/issues/308)
[#316](https://github.com/Ocramius/ProxyManager/issues/316)
- PHP 7.1.0-DEV includes type-checks for incompatible arithmetic operations: some of those operations were erroneously
performed in the library internals. [#308](https://github.com/Ocramius/ProxyManager/issues/308)
## 2.0.1
### Fixed
- Travis-CI environment was fixed to test the library using the minimum dependencies version.
### Added
- Added unit test to make sure that properties skipped should be preserved even being cloned.
## 2.0.0
### BC Breaks
Please refer to [the upgrade documentation](UPGRADE.md) to see which backwards-incompatible
changes were applied to this release.
### New features
#### PHP 7 support
ProxyManager will now correctly operate in PHP 7 environments.
#### PHP 7 Return type hints
ProxyManager will now correctly mimic signatures of methods with return type hints:
```php
class SayHello
{
public function hello() : string
{
return 'hello!';
}
}
```
#### PHP 7 Scalar type hints
ProxyManager will now correctly mimic signatures of methods with scalar type hints
```php
class SayHello
{
public function hello(string $name) : string
{
return 'hello, ' . $name;
}
}
```
#### PHP 5.6 Variadics support
ProxyManager will now correctly mimic behavior of methods with variadic parameters:
```php
class SayHello
{
public function hello(string ...$names) : string
{
return 'hello, ' . implode(', ', $names);
}
}
```
By-ref variadic arguments are also supported:
```php
class SayHello
{
public function hello(string ... & $names)
{
foreach ($names as & $name) {
$name = 'hello, ' . $name;
}
}
}
```
#### Constructors in proxies are not replaced anymore
In ProxyManager v1.x, the constructor of a proxy was completely replaced with a method
accepting proxy-specific parameters.
This is no longer true, and you will be able to use the constructor of your objects as
if the class wasn't proxied at all:
```php
class SayHello
{
public function __construct()
{
echo 'Hello!';
}
}
/* @var $proxyGenerator \ProxyManager\ProxyGenerator\ProxyGeneratorInterface */
$proxyClass = $proxyGenerator->generateProxy(
new ReflectionClass(SayHello::class),
new ClassGenerator('ProxyClassName')
);
eval('<?php ' . $proxyClass->generate());
$proxyName = $proxyClass->getName();
$object = new ProxyClassName(); // echoes "Hello!"
var_dump($object); // a proxy object
```
If you still want to manually build a proxy (without factories), a
`public static staticProxyConstructor` method is added to the generated proxy classes.
#### Friend classes support
You can now access state of "friend objects" at any time.
```php
class EmailAddress
{
private $address;
public function __construct(string $address)
{
assertEmail($address);
$this->address = $address;
}
public function equalsTo(EmailAddress $other)
{
return $this->address === $other->address;
}
}
```
When using lazy-loading or access-interceptors, the `equalsTo` method will
properly work, as even `protected` and `private` access are now correctly proxied.
#### Ghost objects now only lazy-load on state-access
Lazy loading ghost objects now trigger lazy-loading only when their state is accessed.
This also implies that lazy loading ghost objects cannot be used with interfaces anymore.
```php
class AccessPolicy
{
private $policyName;
/**
* Calling this method WILL cause lazy-loading, when using a ghost object,
* as the method is accessing the object's state
*/
public function getPolicyName() : string
{
return $this->policyName;
}
/**
* Calling this method WILL NOT cause lazy-loading, when using a ghost object,
* as the method is not reading any from the object.
*/
public function allowAccess() : bool
{
return false;
}
}
```
#### Faster ghost object state initialization
Lazy loading ghost objects can now be initialized in a more efficient way, by avoiding
reflection or setters:
```php
class Foo
{
private $a;
protected $b;
public $c;
}
$factory = new \ProxyManager\Factory\LazyLoadingGhostFactory();
$proxy = $factory-createProxy(
Foo::class,
function (
GhostObjectInterface $proxy,
string $method,
array $parameters,
& $initializer,
array $properties
) {
$initializer = null;
$properties["\0Foo\0a"] = 'abc';
$properties["\0*\0b"] = 'def';
$properties['c'] = 'ghi';
return true;
}
);
$reflectionA = new ReflectionProperty(Foo::class, 'a');
$reflectionA->setAccessible(true);
var_dump($reflectionA->getValue($proxy)); // dumps "abc"
$reflectionB = new ReflectionProperty(Foo::class, 'b');
$reflectionB->setAccessible(true);
var_dump($reflectionB->getValue($proxy)); // dumps "def"
var_dump($proxy->c); // dumps "ghi"
```
#### Skipping lazy-loaded properties in generated proxies
Lazy loading ghost objects can now skip lazy-loading for certain properties.
This is especially useful when you have properties that are always available,
such as identifiers of entities:
```php
class User
{
private $id;
private $username;
public function getId() : int
{
return $this->id;
}
public function getUsername() : string
{
return $this->username;
}
}
/* @var $proxy User */
$proxy = (new \ProxyManager\Factory\LazyLoadingGhostFactory())->createProxy(
User::class,
function (
GhostObjectInterface $proxy,
string $method,
array $parameters,
& $initializer,
array $properties
) {
$initializer = null;
var_dump('Triggered lazy-loading!');
$properties["\0User\0username"] = 'Ocramius';
return true;
},
[
'skippedProperties' => [
"\0User\0id",
],
]
);
$idReflection = new \ReflectionProperty(User::class, 'id');
$idReflection->setAccessible(true);
$idReflection->setValue($proxy, 123);
var_dump($proxy->getId()); // 123
var_dump($proxy->getUsername()); // "Triggered lazy-loading!", then "Ocramius"
```
#### Proxies are now always generated on-the-fly by default
Proxies are now automatically generated any time you require them: no configuration
needed. If you want to gain better performance, you may still want to read
the [tuning for production docs](docs/tuning-for-production.md).
#### Proxy names are now hashed, simplified signature is attached to them
Proxy classes now have shorter names, as the parameters used to generate them are
hashed into their name. A signature is attached to proxy classes (as a private static
property) so that proxy classes aren't re-used across library updates.
Upgrading ProxyManager will now cause all proxies to be re-generated automatically,
while the old proxy files are going to be ignored.

19
vendor/ocramius/proxy-manager/LICENSE vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2013 Marco Pivetta
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.

55
vendor/ocramius/proxy-manager/README.md vendored Normal file
View File

@@ -0,0 +1,55 @@
# Proxy Manager
This library aims at providing abstraction for generating various kinds of [proxy classes](http://ocramius.github.io/presentations/proxy-pattern-in-php/).
![ProxyManager](https://raw.githubusercontent.com/Ocramius/ProxyManager/917bf1698243a1079aaa27ed8ea08c2aef09f4cb/proxy-manager.png)
[![Build Status](https://travis-ci.org/Ocramius/ProxyManager.png?branch=master)](https://travis-ci.org/Ocramius/ProxyManager)
[![Code Coverage](https://scrutinizer-ci.com/g/Ocramius/ProxyManager/badges/coverage.png?s=ca3b9ceb9e36aeec0e57569cc8983394b7d2a59e)](https://scrutinizer-ci.com/g/Ocramius/ProxyManager/)
[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/Ocramius/ProxyManager/badges/quality-score.png?s=eaa858f876137ed281141b1d1e98acfa739729ed)](https://scrutinizer-ci.com/g/Ocramius/ProxyManager/)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/69fe5f97-b1c8-4ddd-93ce-900b8b788cf2/mini.png)](https://insight.sensiolabs.com/projects/69fe5f97-b1c8-4ddd-93ce-900b8b788cf2)
[![Dependency Status](https://www.versioneye.com/package/php--ocramius--proxy-manager/badge.png)](https://www.versioneye.com/package/php--ocramius--proxy-manager)
[![Reference Status](https://www.versioneye.com/php/ocramius:proxy-manager/reference_badge.svg)](https://www.versioneye.com/php/ocramius:proxy-manager/references)
[![HHVM Status](http://hhvm.h4cc.de/badge/ocramius/proxy-manager.png)](http://hhvm.h4cc.de/package/ocramius/proxy-manager)
[![Total Downloads](https://poser.pugx.org/ocramius/proxy-manager/downloads.png)](https://packagist.org/packages/ocramius/proxy-manager)
[![Latest Stable Version](https://poser.pugx.org/ocramius/proxy-manager/v/stable.png)](https://packagist.org/packages/ocramius/proxy-manager)
[![Latest Unstable Version](https://poser.pugx.org/ocramius/proxy-manager/v/unstable.png)](https://packagist.org/packages/ocramius/proxy-manager)
## Documentation
You can learn about the proxy pattern and how to use the **ProxyManager** in the [docs](docs), which are also
[compiled to HTML](http://ocramius.github.io/ProxyManager).
## Help/Support
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Ocramius/ProxyManager?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
## Installation
The suggested installation method is via [composer](https://getcomposer.org/):
```sh
php composer.phar require ocramius/proxy-manager
```
## Proxy example
Here's how you build a lazy loadable object with ProxyManager using a *Virtual Proxy*
```php
$factory = new \ProxyManager\Factory\LazyLoadingValueHolderFactory();
$proxy = $factory->createProxy(
\MyApp\HeavyComplexObject::class,
function (& $wrappedObject, $proxy, $method, $parameters, & $initializer) {
$wrappedObject = new HeavyComplexObject(); // instantiation logic here
$initializer = null; // turning off further lazy initialization
}
);
$proxy->doFoo();
```
See the [online documentation](http://ocramius.github.io/ProxyManager) for more supported proxy types and examples.

View File

@@ -0,0 +1,23 @@
---
title: Stability
---
This is a list of supported versions, with their expected release/support time-frames:
# 2.0.x
* Release date: 2016-01-30
* Bug fixes: till 2017-01-29
* Security fixes: till 2018-01-29
# 1.0.x
* Release date: 2014-12-12
* Bug fixes: till 2015-12-11
* Security fixes: till 2016-12-11
# 0.5.x
* Release date: 2013-12-01
* Bug fixes: till 2015-03-11
* Security fixes: till 2015-12-11

102
vendor/ocramius/proxy-manager/UPGRADE.md vendored Normal file
View File

@@ -0,0 +1,102 @@
---
title: Upgrade
---
This is a list of backwards compatibility (BC) breaks introduced in ProxyManager:
# 2.0.0
* PHP `~7.0` is now required to use ProxyManager
* HHVM compatibility is not guaranteed, as HHVM is not yet PHP 7 compliant
* All classes and interfaces now use [strict scalar type hints](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration).
If you extended or implemented anything from the `ProxyManager\` namespace, you probably need to change
that code to adapt it to the new signature.
* All classes and interfaces now use [return type declarations](http://php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration).
If you extended or implemented anything from the `ProxyManager\` namespace, you probably need to change
that code to adapt it to the new signature.
* ProxyManager will no longer write proxies to disk by default:
the [`EvaluatingGeneratorStrategy`](src/GeneratorStrategy/EvaluatingGeneratorStrategy.php) is used instead.
If you still want ProxyManager to write files to disk, please refer to the [tuning for production docs](docs/tuning-for-production.md)
* Ghost objects were entirely rewritten, for better support and improved performance. Lazy-loading is not
triggered by public API access, but by property access (private and public). While this is not really a BC
break, you are encouraged to check your applications if you rely on [ghost objects](docs/lazy-loading-ghost-object.md).
* If ProxyManager can't find a proxy, it will now automatically attempt to auto-generate it, regardless of
the settings passed to it.
* `ProxyManager\Configuration#setAutoGenerateProxies()` was removed. Please look for calls to this method and
remove them.
* Private properties are now also correctly handled by ProxyManager: accessing proxy state via friend classes
(protected or private scope) does not require any particular workarounds anymore.
* `ProxyManager\Version::VERSION` was removed. Please use `ProxyManager\Version::getVersion()` instead.
* PHP 4 style constructors are no longer supported
# 1.0.0
`1.0.0` is be fully compatible with `0.5.0`.
# 0.5.0
* The Generated Hydrator has been removed - it is now available as a separate project
at [Ocramius/GeneratedHydrator](https://github.com/Ocramius/GeneratedHydrator) [#65](https://github.com/Ocramius/ProxyManager/pull/65)
* When having a `public function __get($name)` defined (by-val) and public properties, it won't be possible to get public
properties by-ref while initializing the object. Either drop `__get()` or implement
a by-ref `& __get()` [#126](https://github.com/Ocramius/ProxyManager/pull/126)
* Proxies are now being always auto-generated if they could not be autoloaded by a factory. The methods
[`ProxyManager\Configuration#setAutoGenerateProxies()`](https://github.com/Ocramius/ProxyManager/blob/0.5.0-BETA2/src/ProxyManager/Configuration.php#L67)
and [`ProxyManager\Configuration#doesAutoGenerateProxies()`](https://github.com/Ocramius/ProxyManager/blob/0.5.0-BETA2/src/ProxyManager/Configuration.php#L75)
are now no-op and deprecated, and will be removed in the next minor
version [#87](https://github.com/Ocramius/ProxyManager/pull/87) [#90](https://github.com/Ocramius/ProxyManager/pull/90)
* Proxy public properties defaults are now set before initialization [#116](https://github.com/Ocramius/ProxyManager/pull/116) [#122](https://github.com/Ocramius/ProxyManager/pull/122)
# 0.4.0
* An optional parameter `$options` was introduced
in [`ProxyManager\Inflector\ClassNameInflectorInterface#getProxyClassName($className, array $options = array())`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Inflector/ClassNameInflectorInterface.php)
parametrize the generated class name as of [#10](https://github.com/Ocramius/ProxyManager/pull/10)
and [#59](https://github.com/Ocramius/ProxyManager/pull/59)
* Generated hydrators no longer have constructor arguments. Any required reflection instantiation is now dealt with
in the hydrator internally as of [#63](https://github.com/Ocramius/ProxyManager/pull/63)
# 0.3.4
* Interface names are also supported for proxy generation as of [#40](https://github.com/Ocramius/ProxyManager/pull/40)
# 0.3.3
* [Generated hydrators](https://github.com/Ocramius/ProxyManager/tree/master/docs/generated-hydrator.md) were introduced
# 0.3.2
* An additional (optional) [by-ref parameter was added](https://github.com/Ocramius/ProxyManager/pull/31)
to the lazy loading proxies' initializer to allow unsetting the initializer with less overhead.
# 0.3.0
* Dependency to [jms/cg](https://github.com/schmittjoh/cg-library) removed
* Moved code generation logic to [`Zend\Code`](https://github.com/zendframework/zf2)
* Added method [`ProxyManager\Inflector\ClassNameInflectorInterface#isProxyClassName($className)`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Inflector/ClassNameInflectorInterface.php)
* The constructor of [`ProxyManager\Autoloader\Autoloader`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Autoloader/Autoloader.php)
changed from `__construct(\ProxyManager\FileLocator\FileLocatorInterface $fileLocator)` to
`__construct(\ProxyManager\FileLocator\FileLocatorInterface $fileLocator, \ProxyManager\Inflector\ClassNameInflectorInterface $classNameInflector)`
* Classes implementing `CG\Core\GeneratorStrategyInterface` now implement
[`ProxyManager\GeneratorStrategy\GeneratorStrategyInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/GeneratorStrategy/GeneratorStrategyInterface.php)
instead
* All code generation logic has been replaced - If you wrote any logic based on `ProxyManager\ProxyGenerator`, you will
have to rewrite it
# 0.2.0
* The signature of initializers to be used with proxies implementing
[`ProxyManager\Proxy\LazyLoadingInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/LazyLoadingInterface.php)
changed from:
```php
$initializer = function ($proxy, & $wrappedObject, $method, $parameters) {};
```
to
```php
$initializer = function (& $wrappedObject, $proxy, $method, $parameters) {};
```
Only the order of parameters passed to the closures has been changed.

View File

@@ -0,0 +1,56 @@
{
"name": "ocramius/proxy-manager",
"description": "A library providing utilities to generate, instantiate and generally operate with Object Proxies",
"type": "library",
"license": "MIT",
"homepage": "https://github.com/Ocramius/ProxyManager",
"keywords": [
"proxy",
"proxy pattern",
"service proxies",
"lazy loading",
"aop"
],
"authors": [
{
"name": "Marco Pivetta",
"email": "ocramius@gmail.com",
"homepage": "http://ocramius.github.io/"
}
],
"require": {
"php": "7.0.0 - 7.0.5 || ^7.0.7",
"zendframework/zend-code": "3.0.0 - 3.0.2 || ^3.0.4",
"ocramius/package-versions": "^1.0"
},
"require-dev": {
"ext-phar": "*",
"phpunit/phpunit": "^5.4.6",
"squizlabs/php_codesniffer": "^2.6.0",
"couscous/couscous": "^1.4.0",
"phpbench/phpbench": "^0.11.2"
},
"suggest": {
"ocramius/generated-hydrator": "To have very fast object to array to object conversion for ghost objects",
"zendframework/zend-xmlrpc": "To have the XmlRpc adapter (Remote Object feature)",
"zendframework/zend-json": "To have the JsonRpc adapter (Remote Object feature)",
"zendframework/zend-soap": "To have the Soap adapter (Remote Object feature)"
},
"autoload": {
"psr-0": {
"ProxyManager\\": "src"
}
},
"autoload-dev": {
"psr-0": {
"ProxyManagerBench\\": "tests",
"ProxyManagerTest\\": "tests",
"ProxyManagerTestAsset\\": "tests"
}
},
"extra": {
"branch-alias": {
"dev-master": "3.0.x-dev"
}
}
}

View File

@@ -0,0 +1,8 @@
baseUrl: https://ocramius.github.io/ProxyManager
template:
directory: doc-template
exclude:
- vendor
- bin
- tests

View File

@@ -0,0 +1,125 @@
/*
Copyright (c) 2006, Ivan Sagalaev
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of highlight.js nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS AND 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.
*/
.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
background: #444;
-webkit-text-size-adjust: none;
}
.hljs-keyword,
.hljs-literal,
.hljs-change,
.hljs-winutils,
.hljs-flow,
.nginx .hljs-title,
.tex .hljs-special {
color: white;
}
.hljs,
.hljs-subst {
color: #ddd;
}
.hljs-string,
.hljs-title,
.hljs-type,
.ini .hljs-title,
.hljs-tag .hljs-value,
.css .hljs-rules .hljs-value,
.hljs-preprocessor,
.hljs-pragma,
.ruby .hljs-symbol,
.ruby .hljs-symbol .hljs-string,
.ruby .hljs-class .hljs-parent,
.hljs-built_in,
.django .hljs-template_tag,
.django .hljs-variable,
.smalltalk .hljs-class,
.hljs-javadoc,
.ruby .hljs-string,
.django .hljs-filter .hljs-argument,
.smalltalk .hljs-localvars,
.smalltalk .hljs-array,
.hljs-attr_selector,
.hljs-pseudo,
.hljs-addition,
.hljs-stream,
.hljs-envvar,
.apache .hljs-tag,
.apache .hljs-cbracket,
.tex .hljs-command,
.hljs-prompt,
.coffeescript .hljs-attribute {
color: #d88;
}
.hljs-comment,
.hljs-annotation,
.hljs-decorator,
.hljs-pi,
.hljs-doctype,
.hljs-deletion,
.hljs-shebang,
.apache .hljs-sqbracket,
.tex .hljs-formula {
color: #777;
}
.hljs-keyword,
.hljs-literal,
.hljs-title,
.css .hljs-id,
.hljs-phpdoc,
.hljs-dartdoc,
.hljs-type,
.vbscript .hljs-built_in,
.rsl .hljs-built_in,
.smalltalk .hljs-class,
.diff .hljs-header,
.hljs-chunk,
.hljs-winutils,
.bash .hljs-variable,
.apache .hljs-tag,
.tex .hljs-special,
.hljs-request,
.hljs-status {
font-weight: bold;
}
.coffeescript .javascript,
.javascript .xml,
.tex .hljs-formula,
.xml .javascript,
.xml .vbscript,
.xml .css,
.xml .hljs-cdata {
opacity: 0.5;
}

View File

@@ -0,0 +1,179 @@
html { font-family: sans-serif; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; }
body { margin: 0; }
[hidden], template { display: none; }
a { background: transparent; }
a:active, a:hover { outline: 0; }
h1 { font-size: 2em; margin: 0.67em 0; }
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: 'Menlo', 'Monaco', 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; }
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; }
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 { border-radius: 4px; font-size: 15px; padding: 20px; border: 1px solid #EBEBEB; }
.content h1 { padding-bottom: 12px; border-bottom: 1px solid #EFEFEF; margin-bottom: 20px; }
.main-nav ul li{ position: relative;}
.main-nav ul li{ position: relative;}
.main-nav ul li:hover { background: #2F611C;}
.main-nav ul li:hover > ul { display:block }
.main-nav ul li > ul { display:none; position: absolute; list-style: none; width: 100%; z-index: 9;}
.main-nav ul li > ul li a { color: #BFE5F1; display: block; background: #2F611C; padding: 20px;}
.main-nav ul li > ul li a:hover { background: #1C440C;}
/* 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; }
.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; }
.spy-nav select{ width: 100%; margin-bottom: 10px}
.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

@@ -0,0 +1,117 @@
<!DOCTYPE html>
<html class="no-js" id="top">
<head>
<title>ProxyManager Documentation{% if title is defined %} - {{ title }}{% endif %}</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="{{ baseUrl }}/css/main.css" rel="stylesheet" />
<link href="{{ baseUrl }}/css/highlight.dark.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<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="{{ baseUrl }}"><img alt="ProxyManager" src="{{ baseUrl }}/img/block.png" /></a></h1>
<nav class="main-nav" role="navigation">
<ul>
<li><a href="https://github.com/Ocramius/ProxyManager" target="_blank">Github</a></li>
{% if versions is defined %}
<li>
<a href="#">Version</a>
<ul>
{% for key, version in versions.items %}
<li><a href="{{ version.link|e }}">{{ version.name|e }}</a></li>
{% endfor %}
</ul>
</li>
{% endif %}
</ul>
<div class="bcms-clearfix"></div>
</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="{{ baseUrl }}/index.html">Intro</a></li>
<li><a href="{{ baseUrl }}/docs/lazy-loading-value-holder.html">Virtual Proxy</a></li>
<li><a href="{{ baseUrl }}/docs/lazy-loading-ghost-object.html">Ghost Object</a></li>
<li><a href="{{ baseUrl }}/docs/access-interceptor-value-holder.html">Smart Reference</a></li>
<li><a href="{{ baseUrl }}/docs/access-interceptor-scope-localizer.html">Smart Reference<br/>(fluent safe)</a></li>
<li><a href="{{ baseUrl }}/docs/null-object.html">Null Objects</a></li>
<li><a href="{{ baseUrl }}/docs/remote-object.html">Remote Object</a></li>
<li><a href="{{ baseUrl }}/docs/generator-strategies.html">Code Evaluators</a></li>
<li><a href="{{ baseUrl }}/docs/tuning-for-production.html">Tuning for Production</a></li>
</ul>
</nav>
<div class="bcms-clearfix bcms-clearfix"></div>
<a class="btn btn-action btn-full download-component"
href="{{ baseUrl }}/docs/download.html">Download</a>
<div class="bcms-clearfix"></div>
</aside>
<div class="content">
{% block content %}
{{ content|raw }}
{% endblock %}
</div>
</div>
</div>
</section>
</main>
<footer class="site-footer" role="contentinfo">
<div class="container">
<div class="footer-logos">
<ul>
<li><a href="{{ baseUrl }}/stability.html">Stability</a> | </li>
<li><a href="{{ baseUrl }}/upgrade.html">Upgrade Notes</a> | </li>
<li><a href="{{ baseUrl }}/changelog.html">Changelog</a> | </li>
<li><a href="{{ baseUrl }}/contributing.html">Contributing</a> | </li>
<li><a href="{{ baseUrl }}/docs/credits.html">Credits</a> | </li>
<li><a href="{{ baseUrl }}/docs/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.

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

View File

@@ -0,0 +1,111 @@
---
title: Access Interceptor Scope Localizer Proxy
---
# Access Interceptor Scope Localizer Proxy
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.
It works exactly like the [access interceptor value holder](access-interceptor-value-holder.md),
with some minor differences in behavior.
The working concept of an access interceptor scope localizer is to localize scope of a proxied object:
```php
class Example
{
protected $foo;
protected $bar;
protected $baz;
public function doFoo()
{
// ...
}
}
class ExampleProxy extends Example
{
public function __construct(Example $example)
{
$this->foo = & $example->foo;
$this->bar = & $example->bar;
$this->baz = & $example->baz;
}
public function doFoo()
{
return parent::doFoo();
}
}
```
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.
The main advantage of this approach is that the proxy is now safe against fluent interfaces, which
would break an [access interceptor value holder](access-interceptor-value-holder.md) instead.
## Differences with [access interceptor value holder](access-interceptor-value-holder.md):
* It does **NOT** implement the `ProxyManager\Proxy\ValueHolderInterface`, since the proxy itself
does not keep a reference to the original object being proxied
* In all interceptor methods (see [access interceptor value holder](access-interceptor-value-holder.md)),
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.
## Known limitations
* It is **NOT** possible to intercept access to public properties
* It is **NOT** possible to proxy interfaces, since this proxy relies on `parent::method()` calls.
Interfaces obviously don't provide a parent method implementation.
* 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.
* 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
* methods using `func_get_args()`, `func_get_arg()` and `func_num_arg()` will not function properly
for parameters that are not part of the proxied object interface: use
[variadic arguments](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list)
instead.
## Example
Here's an example of how you can create and use an access interceptor scope localizer :
```php
<?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(),
['doFoo' => function () { echo "PreFoo!\n"; }],
['doFoo' => function () { echo "PostFoo!\n"; }]
);
$proxy->doFoo();
```
This send something like following to your output:
```
PreFoo!
Foo!
PostFoo!
```
This is pretty much the same logic that you can find
in [access interceptor value holder](access-interceptor-value-holder.md).

View File

@@ -0,0 +1,117 @@
---
title: Access Interceptor Value Holder Proxy
---
# Access Interceptor Value Holder Proxy
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.
It wraps around a real instance of the object to be proxied, and can be useful for things like:
* caching execution of slow and heavy methods
* log method calls
* debugging
* event triggering
* handling of orthogonal logic, and [AOP](http://en.wikipedia.org/wiki/Aspect-oriented_programming) in general
## Example
Here's an example of how you can create and use an access interceptor value holder:
```php
<?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(),
['doFoo' => function () { echo "PreFoo!\n"; }],
['doFoo' => function () { echo "PostFoo!\n"; }]
);
$proxy->doFoo();
```
This send something like following to your output:
```
PreFoo!
Foo!
PostFoo!
```
## Implementing pre- and post- access interceptors
A proxy produced by the
[`ProxyManager\Factory\AccessInterceptorValueHolderFactory`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Factory/AccessInterceptorValueHolderFactory.php)
implements the
[`ProxyManager\Proxy\AccessInterceptorValueHolderInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/AccessInterceptorValueHolderInterface.php).
Therefore, you can set an access interceptor callback by calling:
```php
$proxy->setMethodPrefixInterceptor('methodName', function () { echo 'pre'; });
$proxy->setMethodSuffixInterceptor('methodName', function () { echo 'post'; });
```
You can also listen to public properties access by attaching interceptors to `__get`, `__set`, `__isset` and `__unset`.
A prefix interceptor (executed before method logic) should have the following signature:
```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, & $returnEarly) {};
```
A suffix interceptor (executed after method logic) should have the following signature:
```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) {};
```
## Known limitations
* methods using `func_get_args()`, `func_get_arg()` and `func_num_arg()` will not function properly
for parameters that are not part of the proxied object interface: use
[variadic arguments](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list)
instead.
## Tuning performance for production
See [Tuning ProxyManager for Production](https://github.com/Ocramius/ProxyManager/blob/master/docs/tuning-for-production.md).

View File

@@ -0,0 +1,15 @@
---
title: License
---
# License
Copyright (c) 2013 Marco Pivetta
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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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.
---

View File

@@ -0,0 +1,26 @@
---
title: Credits
---
# Credits
The idea was originated by a [talk about Proxies in PHP OOP](http://marco-pivetta.com/proxy-pattern-in-php/) that I gave at the [@phpugffm](https://twitter.com/phpugffm) in January 2013.
---
### Contributors
- [Marco Pivetta](https://github.com/Ocramius)
- [Jefersson Nathan](https://github.com/malukenho)
- [Blanchon Vincent](https://github.com/blanchonvincent)
- [Markus Staab](https://github.com/staabm)
- [Gordon Stratton](https://github.com/gws)
- [Prolic](https://github.com/prolic)
- [Guillaume Royer](https://github.com/guilro)
- [Robert Reiz](https://github.com/reiz)
- [Lee Davis](https://github.com/leedavis81)
- [flip111](https://github.com/flip111)
- [Krzysztof Menzyk](https://github.com/krymen)
- [Aleksey Khudyakov](https://github.com/Xerkus)
- [Alexander](https://github.com/asm89)
- [Raul Fraile](https://github.com/raulfraile)

View File

@@ -0,0 +1,11 @@
---
title: Download / Installation
---
## Download / Installation
The suggested installation method is via [composer](https://getcomposer.org/).
```sh
php composer.phar require ocramius/proxy-manager:1.0.*
```

View File

@@ -0,0 +1,20 @@
---
title: Generator strategies
---
# Generator strategies
ProxyManager allows you to generate classes based on generator strategies and a
given `Zend\Code\Generator\ClassGenerator` as of
the [interface of a generator strategy](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/GeneratorStrategy/GeneratorStrategyInterface.php).
Currently, 3 generator strategies are shipped with ProxyManager:
* [`ProxyManager\GeneratorStrategy\BaseGeneratorStrategy`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/GeneratorStrategy/BaseGeneratorStrategy.php),
which simply retrieves the string representation of the class from `ClassGenerator`
* [`ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/GeneratorStrategy/EvaluatingGeneratorStrategy.php),
which calls `eval()` upon the generated class code before returning it. This is useful in cases
where you want to generate multiple classes at runtime
* [`ProxyManager\GeneratorStrategy\FileWriterGeneratorStrategy`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/GeneratorStrategy/FileWriterGeneratorStrategy.php),
which accepts a [`ProxyManager\FileLocator\FileLocatorInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/FileLocator/FileLocatorInterface.php)
instance as constructor parameter, and based on it, writes the generated class to a file before returning its code.

View File

@@ -0,0 +1,408 @@
---
title: Lazy Loading Ghost Object Proxies
---
# Lazy Loading Ghost Object Proxies
A Lazy Loading Ghost is a type of proxy object.
More specifically, it is a fake object that looks exactly like an object
that you want to interact with, but is actually just an empty instance
that gets all properties populated as soon as they are needed.
Those properties do not really exist until the ghost object is actually
initialized.
## Lazy loading with the Ghost Object
In pseudo-code, in userland, [lazy loading](http://www.martinfowler.com/eaaCatalog/lazyLoad.html) in a ghost object
looks like following:
```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;
}
}
}
```
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.
## When do I use a ghost object?
You usually need a ghost object in cases where following applies:
* you are building a small data-mapper and want to lazily load data across associations in your object graph;
* you want to initialize objects representing rows in a large dataset;
* you want to compare instances of lazily initialized objects without the risk of comparing a proxy with a real subject;
* you are aware of the internal state of the object and are confident in working with its internals via reflection
or direct property access.
## Usage examples
[ProxyManager](https://github.com/Ocramius/ProxyManager) provides a factory that creates lazy loading ghost objects.
To use it, follow these steps:
First, define your object's logic without taking care of lazy loading:
```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; }
}
```
Then, use the proxy manager to create a ghost object of it.
You will be responsible for setting its state during lazy loading:
```php
namespace MyApp;
use ProxyManager\Factory\LazyLoadingGhostFactory;
use ProxyManager\Proxy\GhostObjectInterface;
require_once __DIR__ . '/vendor/autoload.php';
$factory = new LazyLoadingGhostFactory();
$initializer = function (
GhostObjectInterface $ghostObject,
string $method,
array $parameters,
& $initializer,
array $properties
) {
$initializer = null; // disable initialization
// load data and modify the object here
$properties["\0MyApp\\Customer\0name"] = 'Agent';
$properties["\0MyApp\\Customer\0surname"] = 'Smith';
// you may also call methods on the object, but remember that
// the constructor was not called yet:
$ghostObject->setSurname('Smith');
return true; // confirm that initialization occurred correctly
};
$ghostObject = $factory->createProxy(\MyApp\Customer::class, $initializer);
```
You can now use your object as before:
```php
// this will work as before
echo $ghostObject->getName() . ' ' . $ghostObject->getSurname(); // Agent Smith
```
## Lazy Initialization
We use a closure to handle lazy initialization of the proxy instance at runtime.
The initializer closure signature for ghost objects is:
```php
/**
* @var object $ghostObject The instance of 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.
* @var array $properties By-ref array with the properties defined in the object, with their
* default values pre-assigned. Keys are in the same format that
* an (array) cast of an object would provide:
* - `"\0Ns\\ClassName\0propertyName"` for `private $propertyName`
* defined on `Ns\ClassName`
* - `"\0Ns\\ClassName\0propertyName"` for `protected $propertyName`
* defined in any level of the hierarchy
* - `"propertyName"` for `public $propertyName`
* defined in any level of the hierarchy
*
* @return bool true on success
*/
$initializer = function (
\ProxyManager\Proxy\GhostObjectInterface $ghostObject,
string $method,
array $parameters,
& $initializer,
array $properties
) {};
```
The initializer closure should usually be coded like following:
```php
$initializer = function (
\ProxyManager\Proxy\GhostObjectInterface $ghostObject,
string $method,
array $parameters,
& $initializer,
array $properties
) {
$initializer = null; // disable initializer for this proxy instance
// initialize properties (please read further on)
$properties["\0ClassName\0foo"] = 'foo';
$properties["\0ClassName\0bar"] = 'bar';
return true; // report success
};
```
### Lazy initialization `$properties` explained
The assignments to properties in this closure use unusual `"\0"` sequences.
This is to be consistent with how PHP represents private and protected properties when
casting an object to an array.
`ProxyManager` simply copies a reference to the properties into the `$properties` array passed to the
initializer, which allows you to set the state of the object without accessing any of its public
API. (This is a very important detail for mapper implementations!)
Specifically:
* `"\0Ns\\ClassName\0propertyName"` means `private $propertyName` defined in `Ns\ClassName`;
* `"\0*\0propertyName"` means `protected $propertyName` defined in any level of the class
hierarchy;
* `"propertyName"` means `public $propertyName` defined in any level of the class hierarchy.
Therefore, given this class:
```php
namespace MyNamespace;
class MyClass
{
private $property1;
protected $property2;
public $property3;
}
```
Its appropriate initialization code would be:
```php
namespace MyApp;
use ProxyManager\Factory\LazyLoadingGhostFactory;
use ProxyManager\Proxy\GhostObjectInterface;
require_once __DIR__ . '/vendor/autoload.php';
$factory = new LazyLoadingGhostFactory();
$initializer = function (
GhostObjectInterface $ghostObject,
string $method,
array $parameters,
& $initializer,
array $properties
) {
$initializer = null;
$properties["\0MyNamespace\\MyClass\0property1"] = 'foo'; //private property of MyNamespace\MyClass
$properties["\0*\0property2"] = 'bar'; //protected property in MyClass's hierarchy
$properties["property3"] = 'baz'; //public property in MyClass's hierarchy
return true;
};
$instance = $factory->createProxy(\MyNamespace\MyClass::class, $initializer);
```
This code would initialize `$property1`, `$property2` and `$property3`
respectively to `"foo"`, `"bar"` and `"baz"`.
You may read the default values for those properties by reading the respective array keys.
Although it is possible to initialize the object by interacting with its public API, it is
not safe to do so, because the object only contains default property values since its constructor was not called.
## Proxy implementation
The
[`ProxyManager\Factory\LazyLoadingGhostFactory`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Factory/LazyLoadingGhostFactory.php)
produces proxies that implement the
[`ProxyManager\Proxy\GhostObjectInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/GhostObjectInterface.php).
At any point in time, you can set a new initializer for the proxy:
```php
$ghostObject->setProxyInitializer($initializer);
```
In your initializer, you **MUST** turn off any further initialization:
```php
$ghostObject->setProxyInitializer(null);
```
or
```php
$initializer = null; // if you use the initializer passed by reference to the closure
```
Remember to call `$ghostObject->setProxyInitializer(null);`, or to set `$initializer = null` inside your
initializer closure to disable initialization of your proxy, or else initialization will trigger
more than once.
## Triggering Initialization
A lazy loading ghost object is initialized whenever you access any of its properties.
Any of the following interactions would trigger lazy initialization:
```php
// calling a method (only if the method accesses internal state)
$ghostObject->someMethod();
// reading a property
echo $ghostObject->someProperty;
// writing a property
$ghostObject->someProperty = 'foo';
// checking for existence of a property
isset($ghostObject->someProperty);
// removing a property
unset($ghostObject->someProperty);
// accessing a property via reflection
$reflection = new \ReflectionProperty($ghostObject, 'someProperty');
$reflection->setAccessible(true);
$reflection->getValue($ghostObject);
// cloning the entire proxy
clone $ghostObject;
// serializing the proxy
$unserialized = unserialize(serialize($ghostObject));
```
A method like following would never trigger lazy loading, in the context of a ghost object:
```php
public function sayHello() : string
{
return 'Look ma! No property accessed!';
}
```
## Skipping properties (properties that should not be initialized)
In some contexts, you may want some properties to be completely ignored by the lazy-loading
system.
An example for that (in data mappers) is entities with identifiers: an identifier is usually
* lightweight
* known at all times
This means that it can be set in our object at all times, and we never need to lazy-load
it. Here is a typical example:
```php
namespace MyApp;
class User
{
private $id;
private $username;
private $passwordHash;
private $email;
private $address;
// ...
public function getId() : int
{
return $this->id;
}
}
```
If we want to skip the property `$id` from lazy-loading, we might want to tell that to
the `LazyLoadingGhostFactory`. Here is a longer example, with a more near-real-world
scenario:
```php
namespace MyApp;
use ProxyManager\Factory\LazyLoadingGhostFactory;
use ProxyManager\Proxy\GhostObjectInterface;
require_once __DIR__ . '/vendor/autoload.php';
$factory = new LazyLoadingGhostFactory();
$initializer = function (
GhostObjectInterface $ghostObject,
string $method,
array $parameters,
& $initializer,
array $properties
) {
$initializer = null;
// note that `getId` won't initialize our proxy here
$properties["\0MyApp\\User\0username"] = $db->fetchField('users', 'username', $ghostObject->getId();
$properties["\0MyApp\\User\0passwordHash"] = $db->fetchField('users', 'passwordHash', $ghostObject->getId();
$properties["\0MyApp\\User\0email"] = $db->fetchField('users', 'email', $ghostObject->getId();
$properties["\0MyApp\\User\0address"] = $db->fetchField('users', 'address', $ghostObject->getId();
return true;
};
$proxyOptions = [
'skippedProperties' => [
"\0MyApp\\User\0id",
],
];
$instance = $factory->createProxy(User::class, $initializer, $proxyOptions);
$idReflection = new \ReflectionProperty(User::class, 'id');
$idReflection->setAccessible(true);
// write the identifier into our ghost object (assuming `setId` doesn't exist)
$idReflection->setValue($instance, 1234);
```
In this example, we pass a `skippedProperties` array to our proxy factory. Note the use of the `"\0"` parameter syntax as described above.
## Proxying interfaces
A lazy loading ghost object cannot proxy an interface directly, as it operates directly around
the state of an object. Use a [Virtual Proxy](lazy-loading-value-holder.md) for that instead.
## Tuning performance for production
See [Tuning ProxyManager for Production](tuning-for-production.md).

View File

@@ -0,0 +1,213 @@
---
title: Lazy Loading Value Holder Proxy
---
# Lazy Loading Value Holder Proxy
A lazy loading value holder proxy is a virtual proxy that wraps and lazily initializes a "real" instance of the proxied
class.
## What is lazy loading?
In pseudo-code, in userland, [lazy loading](http://www.martinfowler.com/eaaCatalog/lazyLoad.html) looks like following:
```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();
}
}
}
```
This code is problematic, and adds a lot of complexity that makes your unit tests' code even worse.
Also, this kind of usage often ends up in coupling your code with a particular
[Dependency Injection Container](http://martinfowler.com/articles/injection.html)
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
[in this article](http://ocramius.github.com/blog/zf2-and-symfony-service-proxies-with-doctrine-proxies/).
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.
## When do I use a lazy value holder?
You usually need a lazy value holder in cases where following applies
* your object takes a lot of time and memory to be initialized (with all dependencies)
* your object is not always used, and the instantiation overhead can be avoided
## Usage examples
[ProxyManager](https://github.com/Ocramius/ProxyManager) provides a factory that eases instantiation of lazy loading
value holders. To use it, follow these steps:
First of all, define your object's logic without taking care of lazy loading:
```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!';
}
}
```
Then use the proxy manager to create a lazy version of the object (as a proxy):
```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
};
$proxy = $factory->createProxy('MyApp\HeavyComplexObject', $initializer);
```
You can now simply use your object as before:
```php
// this will just work as before
$proxy->doFoo(); // OK!
```
## Lazy Initialization
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:
```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 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 (& $wrappedObject, $proxy, $method, array $parameters, & $initializer) {};
```
The initializer closure should usually be coded like following:
```php
$initializer = function (& $wrappedObject, $proxy, $method, array $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
};
```
The
[`ProxyManager\Factory\LazyLoadingValueHolderFactory`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Factory/LazyLoadingValueHolderFactory.php)
produces proxies that implement both the
[`ProxyManager\Proxy\ValueHolderInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/ValueHolderInterface.php)
and the
[`ProxyManager\Proxy\LazyLoadingInterface`](https://github.com/Ocramius/ProxyManager/blob/master/src/ProxyManager/Proxy/LazyLoadingInterface.php).
At any point in time, you can set a new initializer for the proxy:
```php
$proxy->setProxyInitializer($initializer);
```
In your initializer, you currently **MUST** turn off any further initialization:
```php
$proxy->setProxyInitializer(null);
```
or
```php
$initializer = null; // if you use the initializer by reference
```
## Triggering Initialization
A lazy loading proxy is initialized whenever you access any property or method of it.
Any of the following interactions would trigger lazy initialization:
```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));
```
Remember to call `$proxy->setProxyInitializer(null);` to disable initialization of your proxy, or it will happen more
than once.
## Proxying interfaces
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.
## Known limitations
* methods using `func_get_args()`, `func_get_arg()` and `func_num_arg()` will not function properly
for parameters that are not part of the proxied object interface: use
[variadic arguments](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list)
instead.
## Tuning performance for production
See [Tuning ProxyManager for Production](tuning-for-production.md).

View File

@@ -0,0 +1,101 @@
---
title: Null Object Proxy
---
# Null Object Proxy
A Null Object proxy is a [null object pattern](http://en.wikipedia.org/wiki/Null_Object_pattern) implementation.
The proxy factory creates a new object with defined neutral behavior based on an other object, class name or interface.
## What is null object proxy ?
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
wouldn't do anything, therefore offloading client code from doing repetitive checks for ugly null values when the operation
is executed.
## Usage examples
```php
class UserMapper
{
private $adapter;
public function __construct(DatabaseAdapterInterface $adapter) {
$this->adapter = $adapter;
}
public function fetchById($id) {
$this->adapter->select('users', ['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;
}
}
```
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 :
```php
$factory = new \ProxyManager\Factory\NullObjectFactory();
$nullUser = $factory->createProxy('Entity\User');
var_dump($nullUser->getName()); // empty return
```
You can now return a valid entity :
```php
class UserMapper
{
private $adapter;
public function __construct(DatabaseAdapterInterface $adapter) {
$this->adapter = $adapter;
}
public function fetchById($id) {
$this->adapter->select('users', ['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;
}
}
```
## Proxying interfaces
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.
## Tuning performance for production
See [Tuning ProxyManager for Production](tuning-for-production.md).

View File

@@ -0,0 +1,111 @@
---
title: Remote Object Proxy
---
# Remote Object Proxy
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.
## What is remote object proxy ?
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.
## Adapters
ZendFramework's RPC components (XmlRpc, JsonRpc & Soap) can be used easily with the remote object.
You will need to require the one you need via composer, though:
```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.*
```
ProxyManager comes with 3 adapters:
* `ProxyManager\Factory\RemoteObject\Adapter\XmlRpc`
* `ProxyManager\Factory\RemoteObject\Adapter\JsonRpc`
* `ProxyManager\Factory\RemoteObject\Adapter\Soap`
## Usage examples
RPC server side code (`xmlrpc.php` in your local webroot):
```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();
```
Client side code (proxy) :
```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"
```
## Implementing custom adapters
Your adapters must implement `ProxyManager\Factory\RemoteObject\AdapterInterface` :
```php
interface AdapterInterface
{
/**
* Call remote object
*
* @param string $wrappedClass
* @param string $method
* @param array $params
*
* @return mixed
*/
public function call($wrappedClass, $method, array $params = []);
}
```
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
## Known limitations
* methods using `func_get_args()`, `func_get_arg()` and `func_num_arg()` will not function properly
for parameters that are not part of the proxied object interface: use
[variadic arguments](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list)
instead.
## Tuning performance for production
See [Tuning ProxyManager for Production](tuning-for-production.md).

View File

@@ -0,0 +1,28 @@
---
title: Tuning the ProxyManager for production
---
## Tuning the ProxyManager for production
By default, all proxy factories generate the required proxy classes at runtime.
Proxy generation causes I/O operations and uses a lot of reflection, so be sure to have
generated all of your proxies **before deploying your code on a live system**, or you
may experience poor performance.
You can configure ProxyManager so that it will try autoloading the proxies first.
Generating them "bulk" is not yet implemented:
```php
$config = new \ProxyManager\Configuration();
$config->setProxiesTargetDir(__DIR__ . '/my/generated/classes/cache/dir');
// then register the autoloader
spl_autoload_register($config->getProxyAutoloader());
```
Generating a classmap with all your proxy classes in it will also work perfectly.
Please note that all the currently implemented `ProxyManager\Factory\*` classes accept
a `ProxyManager\Configuration` object as optional constructor parameter. This allows for
fine-tuning of ProxyManager according to your needs.

View File

@@ -0,0 +1,10 @@
{
"bootstrap": "vendor/autoload.php",
"path": "tests/ProxyManagerBench",
"retry_threshold": 5,
"reports": {
"report": {
"extends": "aggregate"
}
}
}

View File

@@ -0,0 +1,346 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
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.
-->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="378.25879"
height="241.71141"
id="svg9092"
version="1.1"
inkscape:version="0.48.4 r9939"
sodipodi:docname="logo_DEF.svg">
<title
id="title5929">Logo - Ocramius Proxy Manager</title>
<defs
id="defs9094">
<linearGradient
id="linearGradient3798">
<stop
id="stop3800"
offset="0"
style="stop-color:#545454;stop-opacity:0;" />
<stop
id="stop3802"
offset="1"
style="stop-color:#585858;stop-opacity:1;" />
</linearGradient>
<linearGradient
id="linearGradient3788">
<stop
style="stop-color:#585858;stop-opacity:1;"
offset="0"
id="stop3790" />
<stop
style="stop-color:#585858;stop-opacity:0;"
offset="1"
id="stop3792" />
</linearGradient>
<marker
inkscape:stockid="DotL"
orient="auto"
refY="0"
refX="0"
id="DotL"
style="overflow:visible">
<path
id="path3987"
d="m -2.5,-1 c 0,2.76 -2.24,5 -5,5 -2.76,0 -5,-2.24 -5,-5 0,-2.76 2.24,-5 5,-5 2.76,0 5,2.24 5,5 z"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt"
transform="matrix(0.8,0,0,0.8,5.92,0.8)"
inkscape:connector-curvature="0" />
</marker>
<clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath3920">
<path
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m -21.125,46.0625 c -1.315071,0 -2.375,1.059929 -2.375,2.375 l 0,262.09375 c 0,1.31507 1.059929,2.375 2.375,2.375 l 292.15625,0 c 1.31507,0 2.375,-1.05993 2.375,-2.375 l 0,-262.09375 c 0,-1.315071 -1.05993,-2.375 -2.375,-2.375 l -292.15625,0 z m 111.28125,68.34375 68.625,0 33.9375,58.75 -33.9375,60.15625 -68.625,0 L 55.8125,173.875 90.15625,114.40625 z"
id="path3922"
inkscape:connector-curvature="0" />
</clipPath>
<clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath3924">
<path
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m -21.125,46.0625 c -1.315071,0 -2.375,1.059929 -2.375,2.375 l 0,262.09375 c 0,1.31507 1.059929,2.375 2.375,2.375 l 292.15625,0 c 1.31507,0 2.375,-1.05993 2.375,-2.375 l 0,-262.09375 c 0,-1.315071 -1.05993,-2.375 -2.375,-2.375 l -292.15625,0 z m 111.28125,68.34375 68.625,0 33.9375,58.75 -33.9375,60.15625 -68.625,0 L 55.8125,173.875 90.15625,114.40625 z"
id="path3926"
inkscape:connector-curvature="0" />
</clipPath>
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.53214715"
inkscape:cx="-234.17911"
inkscape:cy="-96.916153"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:snap-bbox="true"
inkscape:bbox-nodes="true"
inkscape:bbox-paths="true"
inkscape:snap-bbox-edge-midpoints="true"
inkscape:snap-bbox-midpoints="true"
inkscape:object-paths="true"
inkscape:object-nodes="true"
inkscape:snap-smooth-nodes="true"
inkscape:snap-midpoints="true"
inkscape:snap-intersection-paths="true"
inkscape:snap-object-midpoints="true"
inkscape:snap-center="true"
inkscape:window-width="1366"
inkscape:window-height="746"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1"
inkscape:snap-global="true"
showguides="true"
inkscape:guide-bbox="true"
inkscape:snap-page="false"
inkscape:snap-grids="false"
inkscape:snap-to-guides="false"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0" />
<metadata
id="metadata9097">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title>Logo - Ocramius Proxy Manager</dc:title>
<dc:date>November 2013</dc:date>
<dc:creator>
<cc:Agent>
<dc:title>Maestro Pivetta</dc:title>
</cc:Agent>
</dc:creator>
<dc:rights>
<cc:Agent>
<dc:title>MIT</dc:title>
</cc:Agent>
</dc:rights>
<dc:publisher>
<cc:Agent>
<dc:title>Marco Pivetta</dc:title>
</cc:Agent>
</dc:publisher>
<dc:coverage>Logo</dc:coverage>
<dc:subject>
<rdf:Bag />
</dc:subject>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:groupmode="layer"
id="layer4"
inkscape:label="Layer"
transform="translate(-18.781538,-53.01103)" />
<g
inkscape:groupmode="layer"
id="layer3"
inkscape:label="low"
style="display:inline"
transform="translate(-18.781538,-53.01103)">
<path
style="fill:none;stroke:#787878;stroke-width:14.46100044;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
d="m 222.81682,230.67946 -98.45761,-56.81264 0,0 -98.347172,56.81265"
id="path3882"
inkscape:connector-curvature="0"
clip-path="url(#clipPath3924)" />
<path
style="fill:none;stroke:#787878;stroke-width:14.46100044;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
d="m 124.35921,173.86682 0.0552,-113.62529"
id="path3785"
inkscape:connector-curvature="0"
clip-path="url(#clipPath3920)" />
</g>
<g
inkscape:label="base"
inkscape:groupmode="layer"
id="layer1"
style="display:inline"
transform="translate(-18.781538,-53.01103)">
<path
style="fill:#1a1a1a;fill-opacity:1;stroke:#1e1e1e;stroke-width:10;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:0;stroke-dasharray:none"
d="m 193.11566,173.86682 59.40231,0"
id="path12544"
inkscape:connector-curvature="0" />
<path
sodipodi:type="star"
style="fill:none;stroke:#787878;stroke-width:35;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:0;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0"
id="path9100"
sodipodi:sides="6"
sodipodi:cx="225.71429"
sodipodi:cy="372.36218"
sodipodi:r1="275.01392"
sodipodi:r2="238.16904"
sodipodi:arg1="-0.52359878"
sodipodi:arg2="0"
inkscape:flatsided="true"
inkscape:rounded="0"
inkscape:randomized="0"
d="m 463.88333,234.85522 0,275.01392 L 225.7143,647.3761 -12.454743,509.86914 -12.454744,234.85523 225.71429,97.348267 z"
transform="matrix(0.41316197,0,0,0.41316197,31.157864,20.020928)"
clip-path="none" />
<path
inkscape:connector-curvature="0"
id="path12548"
d="m 154.2419,173.86682 59.40231,0"
style="fill:#1a1a1a;fill-opacity:1;stroke:#1e1e1e;stroke-width:10;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:0;stroke-dasharray:none" />
<g
id="g5895">
<path
id="path9626"
sodipodi:type="star"
style="fill:none;stroke:#de8c33;stroke-width:57.93455887;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:40"
sodipodi:sides="6"
sodipodi:cx="225.71429"
sodipodi:cy="372.36218"
sodipodi:r1="275.01392"
sodipodi:r2="238.16904"
sodipodi:arg1="-0.52359878"
sodipodi:arg2="0"
inkscape:flatsided="true"
inkscape:rounded="0"
inkscape:randomized="0"
d="m 463.88333,234.85522 0,275.01392 L 225.7143,647.3761 -12.454743,509.86914 -12.454744,234.85523 225.71429,97.348267 z"
transform="matrix(0.21616793,0.12480461,-0.12480461,0.21616793,122.14997,65.203872)" />
<g
style="stroke:#de8c33;stroke-width:4.13199997;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
id="g3786">
<path
inkscape:connector-curvature="0"
style="fill:none;stroke:#de8c33;stroke-width:4.13199997;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:78.84750349"
d="M 158.79266,233.31601 124.46965,173.86682"
id="path9636" />
<path
style="fill:none;stroke:#de8c33;stroke-width:4.13199997;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:78.84750349"
d="m 124.35921,173.86682 34.43344,-59.44919"
id="path3884"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#de8c33;stroke-width:4.13199997;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:78.84750349"
d="m 55.823635,173.86682 68.701185,0.0956"
id="path3886"
inkscape:connector-curvature="0" />
</g>
</g>
<g
id="g5920"
style="fill:#3c3c3c;fill-opacity:1;stroke:#3c3c3c;stroke-width:8;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none">
<path
d="m 163.10781,173.47926 c 0,2.16916 -1.75845,3.92761 -3.9276,3.92761 -2.16916,0 -3.92761,-1.75845 -3.92761,-3.92761 0,-2.16915 1.75845,-3.9276 3.92761,-3.9276 2.16915,0 3.9276,1.75845 3.9276,3.9276 z"
sodipodi:ry="3.9276054"
sodipodi:rx="3.9276054"
sodipodi:cy="173.47926"
sodipodi:cx="159.18021"
id="path5902"
style="fill:#3c3c3c;fill-opacity:1;stroke:#3c3c3c;stroke-width:8;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
sodipodi:type="arc" />
<path
transform="translate(21.523427,0.38755669)"
sodipodi:type="arc"
style="fill:#3c3c3c;fill-opacity:1;stroke:#3c3c3c;stroke-width:8;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
id="path5904"
sodipodi:cx="159.18021"
sodipodi:cy="173.47926"
sodipodi:rx="3.9276054"
sodipodi:ry="3.9276054"
d="m 163.10781,173.47926 c 0,2.16916 -1.75845,3.92761 -3.9276,3.92761 -2.16916,0 -3.92761,-1.75845 -3.92761,-3.92761 0,-2.16915 1.75845,-3.9276 3.92761,-3.9276 2.16915,0 3.9276,1.75845 3.9276,3.9276 z" />
<path
d="m 163.10781,173.47926 c 0,2.16916 -1.75845,3.92761 -3.9276,3.92761 -2.16916,0 -3.92761,-1.75845 -3.92761,-3.92761 0,-2.16915 1.75845,-3.9276 3.92761,-3.9276 2.16915,0 3.9276,1.75845 3.9276,3.9276 z"
sodipodi:ry="3.9276054"
sodipodi:rx="3.9276054"
sodipodi:cy="173.47926"
sodipodi:cx="159.18021"
id="path5906"
style="fill:#3c3c3c;fill-opacity:1;stroke:#3c3c3c;stroke-width:8;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
sodipodi:type="arc"
transform="translate(43.326071,0.38755669)" />
<path
transform="translate(64.819008,1.9726929e-6)"
sodipodi:type="arc"
style="fill:#3c3c3c;fill-opacity:1;stroke:#3c3c3c;stroke-width:8;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
id="path5908"
sodipodi:cx="159.18021"
sodipodi:cy="173.47926"
sodipodi:rx="3.9276054"
sodipodi:ry="3.9276054"
d="m 163.10781,173.47926 c 0,2.16916 -1.75845,3.92761 -3.9276,3.92761 -2.16916,0 -3.92761,-1.75845 -3.92761,-3.92761 0,-2.16915 1.75845,-3.9276 3.92761,-3.9276 2.16915,0 3.9276,1.75845 3.9276,3.9276 z" />
<path
d="m 163.10781,173.47926 c 0,2.16916 -1.75845,3.92761 -3.9276,3.92761 -2.16916,0 -3.92761,-1.75845 -3.92761,-3.92761 0,-2.16915 1.75845,-3.9276 3.92761,-3.9276 2.16915,0 3.9276,1.75845 3.9276,3.9276 z"
sodipodi:ry="3.9276054"
sodipodi:rx="3.9276054"
sodipodi:cy="173.47926"
sodipodi:cx="159.18021"
id="path5910"
style="fill:#3c3c3c;fill-opacity:1;stroke:#3c3c3c;stroke-width:8;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
sodipodi:type="arc"
transform="translate(86.425344,1.9726929e-6)" />
</g>
</g>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="ext cube"
style="display:inline"
transform="translate(-18.781538,-53.01103)">
<g
id="g5891"
style="stroke:#3c3c3c;stroke-opacity:1">
<path
transform="matrix(0.21616793,0.12480461,-0.12480461,0.21616793,318.8443,65.203877)"
d="m 463.88333,234.85522 0,275.01392 L 225.7143,647.3761 -12.454743,509.86914 -12.454744,234.85523 225.71429,97.348267 z"
inkscape:randomized="0"
inkscape:rounded="0"
inkscape:flatsided="true"
sodipodi:arg2="0"
sodipodi:arg1="-0.52359878"
sodipodi:r2="238.16904"
sodipodi:r1="275.01392"
sodipodi:cy="372.36218"
sodipodi:cx="225.71429"
sodipodi:sides="6"
id="path9660"
style="fill:none;stroke:#3c3c3c;stroke-width:57.93323135;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:0;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0"
sodipodi:type="star" />
<path
id="path9662"
style="fill:none;stroke:#3c3c3c;stroke-width:4.13161993;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
d="m 252.51797,173.86682 68.64601,0 34.323,-59.44919 m 10e-6,118.89838 -34.32301,-59.44919"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccccc" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,72 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Autoloader;
use ProxyManager\FileLocator\FileLocatorInterface;
use ProxyManager\Inflector\ClassNameInflectorInterface;
/**
* {@inheritDoc}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class Autoloader implements AutoloaderInterface
{
/**
* @var \ProxyManager\FileLocator\FileLocatorInterface
*/
protected $fileLocator;
/**
* @var \ProxyManager\Inflector\ClassNameInflectorInterface
*/
protected $classNameInflector;
/**
* @param \ProxyManager\FileLocator\FileLocatorInterface $fileLocator
* @param \ProxyManager\Inflector\ClassNameInflectorInterface $classNameInflector
*/
public function __construct(FileLocatorInterface $fileLocator, ClassNameInflectorInterface $classNameInflector)
{
$this->fileLocator = $fileLocator;
$this->classNameInflector = $classNameInflector;
}
/**
* {@inheritDoc}
*/
public function __invoke(string $className) : bool
{
if (class_exists($className, false) || ! $this->classNameInflector->isProxyClassName($className)) {
return false;
}
$file = $this->fileLocator->getProxyFileName($className);
if (! file_exists($file)) {
return false;
}
/* @noinspection PhpIncludeInspection */
return (bool) require_once $file;
}
}

View File

@@ -0,0 +1,39 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Autoloader;
/**
* Basic autoloader utilities required to work with proxy files
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface AutoloaderInterface
{
/**
* Callback to allow the object to be handled as autoloader - tries to autoload the given class name
*
* @param string $className
*
* @return bool
*/
public function __invoke(string $className) : bool;
}

View File

@@ -0,0 +1,214 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager;
use ProxyManager\Autoloader\Autoloader;
use ProxyManager\Autoloader\AutoloaderInterface;
use ProxyManager\FileLocator\FileLocator;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\GeneratorStrategy\GeneratorStrategyInterface;
use ProxyManager\Inflector\ClassNameInflector;
use ProxyManager\Inflector\ClassNameInflectorInterface;
use ProxyManager\Signature\ClassSignatureGenerator;
use ProxyManager\Signature\ClassSignatureGeneratorInterface;
use ProxyManager\Signature\SignatureChecker;
use ProxyManager\Signature\SignatureCheckerInterface;
use ProxyManager\Signature\SignatureGenerator;
use ProxyManager\Signature\SignatureGeneratorInterface;
/**
* Base configuration class for the proxy manager - serves as micro disposable DIC/facade
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class Configuration
{
const DEFAULT_PROXY_NAMESPACE = 'ProxyManagerGeneratedProxy';
/**
* @var string|null
*/
protected $proxiesTargetDir;
/**
* @var string
*/
protected $proxiesNamespace = self::DEFAULT_PROXY_NAMESPACE;
/**
* @var GeneratorStrategyInterface|null
*/
protected $generatorStrategy;
/**
* @var callable|null
*/
protected $proxyAutoloader;
/**
* @var ClassNameInflectorInterface|null
*/
protected $classNameInflector;
/**
* @var SignatureGeneratorInterface|null
*/
protected $signatureGenerator;
/**
* @var SignatureCheckerInterface|null
*/
protected $signatureChecker;
/**
* @var ClassSignatureGeneratorInterface|null
*/
protected $classSignatureGenerator;
/**
* @param AutoloaderInterface $proxyAutoloader
*
* @return void
*/
public function setProxyAutoloader(AutoloaderInterface $proxyAutoloader)
{
$this->proxyAutoloader = $proxyAutoloader;
}
public function getProxyAutoloader() : AutoloaderInterface
{
return $this->proxyAutoloader
?: $this->proxyAutoloader = new Autoloader(
new FileLocator($this->getProxiesTargetDir()),
$this->getClassNameInflector()
);
}
/**
* @param string $proxiesNamespace
*
* @return void
*/
public function setProxiesNamespace(string $proxiesNamespace)
{
$this->proxiesNamespace = $proxiesNamespace;
}
public function getProxiesNamespace() : string
{
return $this->proxiesNamespace;
}
/**
* @param string $proxiesTargetDir
*
* @return void
*/
public function setProxiesTargetDir(string $proxiesTargetDir)
{
$this->proxiesTargetDir = $proxiesTargetDir;
}
public function getProxiesTargetDir() : string
{
return $this->proxiesTargetDir ?: $this->proxiesTargetDir = sys_get_temp_dir();
}
/**
* @param GeneratorStrategyInterface $generatorStrategy
*
* @return void
*/
public function setGeneratorStrategy(GeneratorStrategyInterface $generatorStrategy)
{
$this->generatorStrategy = $generatorStrategy;
}
public function getGeneratorStrategy() : GeneratorStrategyInterface
{
return $this->generatorStrategy
?: $this->generatorStrategy = new EvaluatingGeneratorStrategy();
}
/**
* @param ClassNameInflectorInterface $classNameInflector
*
* @return void
*/
public function setClassNameInflector(ClassNameInflectorInterface $classNameInflector)
{
$this->classNameInflector = $classNameInflector;
}
public function getClassNameInflector() : ClassNameInflectorInterface
{
return $this->classNameInflector
?: $this->classNameInflector = new ClassNameInflector($this->getProxiesNamespace());
}
/**
* @param SignatureGeneratorInterface $signatureGenerator
*
* @return void
*/
public function setSignatureGenerator(SignatureGeneratorInterface $signatureGenerator)
{
$this->signatureGenerator = $signatureGenerator;
}
public function getSignatureGenerator() : SignatureGeneratorInterface
{
return $this->signatureGenerator ?: $this->signatureGenerator = new SignatureGenerator();
}
/**
* @param SignatureCheckerInterface $signatureChecker
*
* @return void
*/
public function setSignatureChecker(SignatureCheckerInterface $signatureChecker)
{
$this->signatureChecker = $signatureChecker;
}
public function getSignatureChecker() : SignatureCheckerInterface
{
return $this->signatureChecker
?: $this->signatureChecker = new SignatureChecker($this->getSignatureGenerator());
}
/**
* @param ClassSignatureGeneratorInterface $classSignatureGenerator
*
* @return void
*/
public function setClassSignatureGenerator(ClassSignatureGeneratorInterface $classSignatureGenerator)
{
$this->classSignatureGenerator = $classSignatureGenerator;
}
public function getClassSignatureGenerator() : ClassSignatureGeneratorInterface
{
return $this->classSignatureGenerator
?: new ClassSignatureGenerator($this->getSignatureGenerator());
}
}

View File

@@ -0,0 +1,39 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Exception;
use BadMethodCallException;
/**
* Exception for forcefully disabled methods
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class DisabledMethodException extends BadMethodCallException implements ExceptionInterface
{
const NAME = __CLASS__;
public static function disabledMethod(string $method) : self
{
return new self(sprintf('Method "%s" is forcefully disabled', $method));
}
}

View File

@@ -0,0 +1,31 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Exception;
/**
* Base exception class for the proxy manager
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface ExceptionInterface
{
}

View File

@@ -0,0 +1,62 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Exception;
use UnexpectedValueException;
/**
* Exception for non writable files
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class FileNotWritableException extends UnexpectedValueException implements ExceptionInterface
{
public static function fromInvalidMoveOperation(string $fromPath, string $toPath) : self
{
return new self(sprintf(
'Could not move file "%s" to location "%s": '
. 'either the source file is not readable, or the destination is not writable',
$fromPath,
$toPath
));
}
public static function fromNonWritableLocation($path) : self
{
$messages = [];
$destination = realpath($path);
if (! $destination) {
$messages[] = 'path does not exist';
}
if ($destination && ! is_file($destination)) {
$messages[] = 'exists and is not a file';
}
if ($destination && ! is_writable($destination)) {
$messages[] = 'is not writable';
}
return new self(sprintf('Could not write to path "%s": %s', $path, implode(', ', $messages)));
}
}

View File

@@ -0,0 +1,66 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Exception;
use InvalidArgumentException;
use ReflectionClass;
use ReflectionMethod;
/**
* Exception for invalid proxied classes
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class InvalidProxiedClassException extends InvalidArgumentException implements ExceptionInterface
{
public static function interfaceNotSupported(ReflectionClass $reflection) : self
{
return new self(sprintf('Provided interface "%s" cannot be proxied', $reflection->getName()));
}
public static function finalClassNotSupported(ReflectionClass $reflection) : self
{
return new self(sprintf('Provided class "%s" is final and cannot be proxied', $reflection->getName()));
}
public static function abstractProtectedMethodsNotSupported(ReflectionClass $reflection) : self
{
return new self(sprintf(
'Provided class "%s" has following protected abstract methods, and therefore cannot be proxied:' . "\n%s",
$reflection->getName(),
implode(
"\n",
array_map(
function (ReflectionMethod $reflectionMethod) : string {
return $reflectionMethod->getDeclaringClass()->getName() . '::' . $reflectionMethod->getName();
},
array_filter(
$reflection->getMethods(),
function (ReflectionMethod $method) : bool {
return $method->isAbstract() && $method->isProtected();
}
)
)
)
));
}
}

View File

@@ -0,0 +1,37 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Exception;
use InvalidArgumentException;
/**
* Exception for invalid directories
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class InvalidProxyDirectoryException extends InvalidArgumentException implements ExceptionInterface
{
public static function proxyDirectoryNotFound(string $directory) : self
{
return new self(sprintf('Provided directory "%s" does not exist', $directory));
}
}

View File

@@ -0,0 +1,44 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Exception;
use LogicException;
use ReflectionProperty;
/**
* Exception for invalid proxied classes
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class UnsupportedProxiedClassException extends LogicException implements ExceptionInterface
{
public static function unsupportedLocalizedReflectionProperty(ReflectionProperty $property) : self
{
return new self(
sprintf(
'Provided reflection property "%s" of class "%s" is private and cannot be localized in PHP 5.3',
$property->getName(),
$property->getDeclaringClass()->getName()
)
);
}
}

View File

@@ -0,0 +1,129 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory;
use ProxyManager\Configuration;
use ProxyManager\Generator\ClassGenerator;
use ProxyManager\ProxyGenerator\ProxyGeneratorInterface;
use ProxyManager\Version;
use ReflectionClass;
/**
* Base factory common logic
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
abstract class AbstractBaseFactory
{
/**
* @var \ProxyManager\Configuration
*/
protected $configuration;
/**
* Cached checked class names
*
* @var string[]
*/
private $checkedClasses = [];
/**
* @param \ProxyManager\Configuration $configuration
*/
public function __construct(Configuration $configuration = null)
{
$this->configuration = $configuration ?: new Configuration();
}
/**
* Generate a proxy from a class name
*
* @param string $className
* @param mixed[] $proxyOptions
*
* @return string proxy class name
*/
protected function generateProxy(string $className, array $proxyOptions = []) : string
{
if (isset($this->checkedClasses[$className])) {
return $this->checkedClasses[$className];
}
$proxyParameters = [
'className' => $className,
'factory' => get_class($this),
'proxyManagerVersion' => Version::getVersion(),
];
$proxyClassName = $this
->configuration
->getClassNameInflector()
->getProxyClassName($className, $proxyParameters);
if (! class_exists($proxyClassName)) {
$this->generateProxyClass(
$proxyClassName,
$className,
$proxyParameters,
$proxyOptions
);
}
$this
->configuration
->getSignatureChecker()
->checkSignature(new ReflectionClass($proxyClassName), $proxyParameters);
return $this->checkedClasses[$className] = $proxyClassName;
}
abstract protected function getGenerator() : ProxyGeneratorInterface;
/**
* Generates the provided `$proxyClassName` from the given `$className` and `$proxyParameters`
*
* @param string $proxyClassName
* @param string $className
* @param array $proxyParameters
* @param mixed[] $proxyOptions
*
* @return void
*/
private function generateProxyClass(
string $proxyClassName,
string $className,
array $proxyParameters,
array $proxyOptions = []
) {
$className = $this->configuration->getClassNameInflector()->getUserClassName($className);
$phpClass = new ClassGenerator($proxyClassName);
$this->getGenerator()->generate(new ReflectionClass($className), $phpClass, $proxyOptions);
$phpClass = $this->configuration->getClassSignatureGenerator()->addSignature($phpClass, $proxyParameters);
$this->configuration->getGeneratorStrategy()->generate($phpClass, $proxyOptions);
$autoloader = $this->configuration->getProxyAutoloader();
$autoloader($proxyClassName);
}
}

View File

@@ -0,0 +1,66 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory;
use ProxyManager\Proxy\AccessInterceptorInterface;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizerGenerator;
use ProxyManager\ProxyGenerator\ProxyGeneratorInterface;
/**
* Factory responsible of producing proxy objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class AccessInterceptorScopeLocalizerFactory extends AbstractBaseFactory
{
/**
* @var \ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizerGenerator|null
*/
private $generator;
/**
* @param object $instance the object to be localized within the access interceptor
* @param \Closure[] $prefixInterceptors an array (indexed by method name) of interceptor closures to be called
* before method logic is executed
* @param \Closure[] $suffixInterceptors an array (indexed by method name) of interceptor closures to be called
* after method logic is executed
*
* @return AccessInterceptorInterface
*/
public function createProxy(
$instance,
array $prefixInterceptors = [],
array $suffixInterceptors = []
) : AccessInterceptorInterface {
$proxyClassName = $this->generateProxy(get_class($instance));
return $proxyClassName::staticProxyConstructor($instance, $prefixInterceptors, $suffixInterceptors);
}
/**
* {@inheritDoc}
*/
protected function getGenerator() : ProxyGeneratorInterface
{
return $this->generator ?: $this->generator = new AccessInterceptorScopeLocalizerGenerator();
}
}

View File

@@ -0,0 +1,66 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory;
use ProxyManager\Proxy\AccessInterceptorValueHolderInterface;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolderGenerator;
use ProxyManager\ProxyGenerator\ProxyGeneratorInterface;
/**
* Factory responsible of producing proxy objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class AccessInterceptorValueHolderFactory extends AbstractBaseFactory
{
/**
* @var \ProxyManager\ProxyGenerator\AccessInterceptorValueHolderGenerator|null
*/
private $generator;
/**
* @param object $instance the object to be wrapped within the value holder
* @param \Closure[] $prefixInterceptors an array (indexed by method name) of interceptor closures to be called
* before method logic is executed
* @param \Closure[] $suffixInterceptors an array (indexed by method name) of interceptor closures to be called
* after method logic is executed
*
* @return AccessInterceptorValueHolderInterface
*/
public function createProxy(
$instance,
array $prefixInterceptors = [],
array $suffixInterceptors = []
) : AccessInterceptorValueHolderInterface {
$proxyClassName = $this->generateProxy(get_class($instance));
return $proxyClassName::staticProxyConstructor($instance, $prefixInterceptors, $suffixInterceptors);
}
/**
* {@inheritDoc}
*/
protected function getGenerator() : ProxyGeneratorInterface
{
return $this->generator ?: $this->generator = new AccessInterceptorValueHolderGenerator();
}
}

View File

@@ -0,0 +1,96 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory;
use Closure;
use ProxyManager\Proxy\GhostObjectInterface;
use ProxyManager\ProxyGenerator\LazyLoadingGhostGenerator;
use ProxyManager\ProxyGenerator\ProxyGeneratorInterface;
/**
* Factory responsible of producing ghost instances
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class LazyLoadingGhostFactory extends AbstractBaseFactory
{
/**
* @var \ProxyManager\ProxyGenerator\LazyLoadingGhostGenerator|null
*/
private $generator;
/**
* {@inheritDoc}
*/
protected function getGenerator() : ProxyGeneratorInterface
{
return $this->generator ?: $this->generator = new LazyLoadingGhostGenerator();
}
/**
* Creates a new lazy proxy instance of the given class with
* the given initializer
*
* Please refer to the following documentation when using this method:
*
* @link https://github.com/Ocramius/ProxyManager/blob/master/docs/lazy-loading-ghost-object.md
*
* @param string $className name of the class to be proxied
* @param Closure $initializer initializer to be passed to the proxy. The initializer closure should have following
* signature:
*
* <code>
* $initializer = function (
* GhostObjectInterface $proxy,
* string $method,
* array $parameters,
* & $initializer,
* array $properties
* ) {};
* </code>
*
* Where:
* - $proxy is the proxy instance on which the initializer is acting
* - $method is the name of the method that triggered the lazy initialization
* - $parameters are the parameters that were passed to $method
* - $initializer by-ref initializer - should be assigned null in the initializer body
* - $properties a by-ref map of the properties of the object, indexed by PHP
* internal property name. Assign values to it to initialize the
* object state
*
* @param mixed[] $proxyOptions a set of options to be used when generating the proxy. Currently supports only
* key "skippedProperties", which allows to skip lazy-loading of some properties.
* "skippedProperties" is a string[], containing a list of properties referenced
* via PHP's internal property name (i.e. "\0ClassName\0propertyName")
*
* @return GhostObjectInterface
*/
public function createProxy(
string $className,
Closure $initializer,
array $proxyOptions = []
) : GhostObjectInterface {
$proxyClassName = $this->generateProxy($className, $proxyOptions);
return $proxyClassName::staticProxyConstructor($initializer);
}
}

View File

@@ -0,0 +1,57 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory;
use ProxyManager\Proxy\VirtualProxyInterface;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator;
use ProxyManager\ProxyGenerator\ProxyGeneratorInterface;
/**
* Factory responsible of producing virtual proxy instances
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class LazyLoadingValueHolderFactory extends AbstractBaseFactory
{
/**
* @var \ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator|null
*/
private $generator;
public function createProxy(
string $className,
\Closure $initializer,
array $proxyOptions = []
) : VirtualProxyInterface {
$proxyClassName = $this->generateProxy($className, $proxyOptions);
return $proxyClassName::staticProxyConstructor($initializer);
}
/**
* {@inheritDoc}
*/
protected function getGenerator() : ProxyGeneratorInterface
{
return $this->generator ?: $this->generator = new LazyLoadingValueHolderGenerator();
}
}

View File

@@ -0,0 +1,60 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory;
use ProxyManager\Proxy\NullObjectInterface;
use ProxyManager\ProxyGenerator\NullObjectGenerator;
use ProxyManager\ProxyGenerator\ProxyGeneratorInterface;
/**
* Factory responsible of producing proxy objects
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
class NullObjectFactory extends AbstractBaseFactory
{
/**
* @var \ProxyManager\ProxyGenerator\NullObjectGenerator|null
*/
private $generator;
/**
* @param object $instanceOrClassName the object to be wrapped or interface to transform to null object
*
* @return NullObjectInterface
*/
public function createProxy($instanceOrClassName) : NullObjectInterface
{
$className = is_object($instanceOrClassName) ? get_class($instanceOrClassName) : $instanceOrClassName;
$proxyClassName = $this->generateProxy($className);
return $proxyClassName::staticProxyConstructor();
}
/**
* {@inheritDoc}
*/
protected function getGenerator() : ProxyGeneratorInterface
{
return $this->generator ?: $this->generator = new NullObjectGenerator();
}
}

View File

@@ -0,0 +1,83 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory\RemoteObject\Adapter;
use ProxyManager\Factory\RemoteObject\AdapterInterface;
use Zend\Server\Client;
/**
* Remote Object base adapter
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
abstract class BaseAdapter implements AdapterInterface
{
/**
* Adapter client
*
* @var \Zend\Server\Client
*/
protected $client;
/**
* Service name mapping
*
* @var string[]
*/
protected $map = [];
/**
* Constructor
*
* @param Client $client
* @param array $map map of service names to their aliases
*/
public function __construct(Client $client, array $map = [])
{
$this->client = $client;
$this->map = $map;
}
/**
* {@inheritDoc}
*/
public function call(string $wrappedClass, string $method, array $params = [])
{
$serviceName = $this->getServiceName($wrappedClass, $method);
if (isset($this->map[$serviceName])) {
$serviceName = $this->map[$serviceName];
}
return $this->client->call($serviceName, $params);
}
/**
* Get the service name will be used by the adapter
*
* @param string $wrappedClass
* @param string $method
*
* @return string Service name
*/
abstract protected function getServiceName(string $wrappedClass, string $method) : string;
}

View File

@@ -0,0 +1,38 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory\RemoteObject\Adapter;
/**
* Remote Object JSON RPC adapter
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
class JsonRpc extends BaseAdapter
{
/**
* {@inheritDoc}
*/
protected function getServiceName(string $wrappedClass, string $method) : string
{
return $wrappedClass . '.' . $method;
}
}

View File

@@ -0,0 +1,38 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory\RemoteObject\Adapter;
/**
* Remote Object SOAP adapter
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
class Soap extends BaseAdapter
{
/**
* {@inheritDoc}
*/
protected function getServiceName(string $wrappedClass, string $method) : string
{
return $method;
}
}

View File

@@ -0,0 +1,38 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory\RemoteObject\Adapter;
/**
* Remote Object XML RPC adapter
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
class XmlRpc extends BaseAdapter
{
/**
* {@inheritDoc}
*/
protected function getServiceName(string $wrappedClass, string $method) : string
{
return $wrappedClass . '.' . $method;
}
}

View File

@@ -0,0 +1,39 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory\RemoteObject;
/**
* Remote Object adapter interface
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
interface AdapterInterface
{
/**
* Call remote object
*
* @param string $wrappedClass
* @param string $method
* @param array $params
*/
public function call(string $wrappedClass, string $method, array $params = []);
}

View File

@@ -0,0 +1,81 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Factory;
use ProxyManager\Configuration;
use ProxyManager\Factory\RemoteObject\AdapterInterface;
use ProxyManager\Proxy\RemoteObjectInterface;
use ProxyManager\ProxyGenerator\ProxyGeneratorInterface;
use ProxyManager\ProxyGenerator\RemoteObjectGenerator;
/**
* Factory responsible of producing remote proxy objects
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
class RemoteObjectFactory extends AbstractBaseFactory
{
/**
* @var AdapterInterface
*/
protected $adapter;
/**
* @var \ProxyManager\ProxyGenerator\RemoteObjectGenerator|null
*/
private $generator;
/**
* {@inheritDoc}
*
* @param AdapterInterface $adapter
* @param Configuration $configuration
*/
public function __construct(AdapterInterface $adapter, Configuration $configuration = null)
{
parent::__construct($configuration);
$this->adapter = $adapter;
}
/**
* @param string|object $instanceOrClassName
*
* @return RemoteObjectInterface
*/
public function createProxy($instanceOrClassName) : RemoteObjectInterface
{
$proxyClassName = $this->generateProxy(
is_object($instanceOrClassName) ? get_class($instanceOrClassName) : $instanceOrClassName
);
return $proxyClassName::staticProxyConstructor($this->adapter);
}
/**
* {@inheritDoc}
*/
protected function getGenerator() : ProxyGeneratorInterface
{
return $this->generator ?: $this->generator = new RemoteObjectGenerator();
}
}

View File

@@ -0,0 +1,59 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\FileLocator;
use ProxyManager\Exception\InvalidProxyDirectoryException;
/**
* {@inheritDoc}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class FileLocator implements FileLocatorInterface
{
/**
* @var string
*/
protected $proxiesDirectory;
/**
* @param string $proxiesDirectory
*
* @throws \ProxyManager\Exception\InvalidProxyDirectoryException
*/
public function __construct(string $proxiesDirectory)
{
$this->proxiesDirectory = realpath($proxiesDirectory);
if (false === $this->proxiesDirectory) {
throw InvalidProxyDirectoryException::proxyDirectoryNotFound($proxiesDirectory);
}
}
/**
* {@inheritDoc}
*/
public function getProxyFileName(string $className) : string
{
return $this->proxiesDirectory . DIRECTORY_SEPARATOR . str_replace('\\', '', $className) . '.php';
}
}

View File

@@ -0,0 +1,39 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\FileLocator;
/**
* Basic autoloader utilities required to work with proxy files
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface FileLocatorInterface
{
/**
* Retrieves the file name for the given proxy
*
* @param string $className
*
* @return string
*/
public function getProxyFileName(string $className) : string;
}

View File

@@ -0,0 +1,56 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Generator;
use Zend\Code\Generator\ClassGenerator as ZendClassGenerator;
/**
* Class generator that ensures that interfaces/classes that are implemented/extended are FQCNs
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class ClassGenerator extends ZendClassGenerator
{
/**
* {@inheritDoc}
*/
public function setExtendedClass($extendedClass) : self
{
if ($extendedClass) {
$extendedClass = '\\' . trim($extendedClass, '\\');
}
return parent::setExtendedClass($extendedClass);
}
/**
* {@inheritDoc}
*/
public function setImplementedInterfaces(array $interfaces) : self
{
foreach ($interfaces as & $interface) {
$interface = '\\' . trim($interface, '\\');
}
return parent::setImplementedInterfaces($interfaces);
}
}

View File

@@ -0,0 +1,54 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Generator;
use ReflectionClass;
/**
* Method generator for magic methods
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicMethodGenerator extends MethodGenerator
{
/**
* @param ReflectionClass $originalClass
* @param string $name
* @param array $parameters
*/
public function __construct(ReflectionClass $originalClass, string $name, array $parameters = [])
{
parent::__construct(
$name,
$parameters,
static::FLAG_PUBLIC,
null,
$originalClass->hasMethod($name) ? '{@inheritDoc}' : null
);
$this->setReturnsReference(strtolower($name) === '__get');
if ($originalClass->hasMethod($name)) {
$this->setReturnsReference($originalClass->getMethod($name)->returnsReference());
}
}
}

View File

@@ -0,0 +1,45 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Generator;
use Zend\Code\Generator\MethodGenerator as ZendMethodGenerator;
use Zend\Code\Reflection\MethodReflection;
/**
* Method generator that fixes minor quirks in ZF2's method generator
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MethodGenerator extends ZendMethodGenerator
{
/**
* {@inheritDoc}
*/
public static function fromReflection(MethodReflection $reflectionMethod) : self
{
$method = parent::fromReflection($reflectionMethod);
$method->setInterface(false);
return $method;
}
}

View File

@@ -0,0 +1,50 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Generator\Util;
use ReflectionClass;
use Zend\Code\Generator\ClassGenerator;
use Zend\Code\Generator\MethodGenerator;
/**
* Util class to help to generate code
*
* @author Jefersson Nathan <malukenho@phpse.net>
* @license MIT
*/
final class ClassGeneratorUtils
{
public static function addMethodIfNotFinal(
ReflectionClass $originalClass,
ClassGenerator $classGenerator,
MethodGenerator $generatedMethod
) : bool {
$methodName = $generatedMethod->getName();
if ($originalClass->hasMethod($methodName) && $originalClass->getMethod($methodName)->isFinal()) {
return false;
}
$classGenerator->addMethodFromGenerator($generatedMethod);
return true;
}
}

View File

@@ -0,0 +1,55 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Generator\Util;
/**
* Utility class capable of generating unique
* valid class/property/method identifiers
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
abstract class UniqueIdentifierGenerator
{
const VALID_IDENTIFIER_FORMAT = '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/';
const DEFAULT_IDENTIFIER = 'g';
/**
* Generates a valid unique identifier from the given name
*
* @param string $name
*
* @return string
*/
public static function getIdentifier(string $name) : string
{
return str_replace(
'.',
'',
uniqid(
preg_match(static::VALID_IDENTIFIER_FORMAT, $name)
? $name
: static::DEFAULT_IDENTIFIER,
true
)
);
}
}

View File

@@ -0,0 +1,40 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\GeneratorStrategy;
use Zend\Code\Generator\ClassGenerator;
/**
* Generator strategy that generates the class body
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class BaseGeneratorStrategy implements GeneratorStrategyInterface
{
/**
* {@inheritDoc}
*/
public function generate(ClassGenerator $classGenerator) : string
{
return $classGenerator->generate();
}
}

View File

@@ -0,0 +1,72 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\GeneratorStrategy;
use Zend\Code\Generator\ClassGenerator;
/**
* Generator strategy that produces the code and evaluates it at runtime
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class EvaluatingGeneratorStrategy implements GeneratorStrategyInterface
{
/**
* @var bool flag indicating whether {@see eval} can be used
*/
private $canEval = true;
/**
* Constructor
*/
public function __construct()
{
$this->canEval = ! ini_get('suhosin.executor.disable_eval');
}
/**
* Evaluates the generated code before returning it
*
* {@inheritDoc}
*/
public function generate(ClassGenerator $classGenerator) : string
{
$code = $classGenerator->generate();
if (! $this->canEval) {
// @codeCoverageIgnoreStart
$fileName = sys_get_temp_dir() . '/EvaluatingGeneratorStrategy.php.tmp.' . uniqid('', true);
file_put_contents($fileName, "<?php\n" . $code);
/* @noinspection PhpIncludeInspection */
require $fileName;
unlink($fileName);
return $code;
// @codeCoverageIgnoreEnd
}
eval($code);
return $code;
}
}

View File

@@ -0,0 +1,107 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\GeneratorStrategy;
use ProxyManager\Exception\FileNotWritableException;
use ProxyManager\FileLocator\FileLocatorInterface;
use Zend\Code\Generator\ClassGenerator;
/**
* Generator strategy that writes the generated classes to disk while generating them
*
* {@inheritDoc}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class FileWriterGeneratorStrategy implements GeneratorStrategyInterface
{
/**
* @var \ProxyManager\FileLocator\FileLocatorInterface
*/
protected $fileLocator;
/**
* @var callable
*/
private $emptyErrorHandler;
/**
* @param \ProxyManager\FileLocator\FileLocatorInterface $fileLocator
*/
public function __construct(FileLocatorInterface $fileLocator)
{
$this->fileLocator = $fileLocator;
$this->emptyErrorHandler = function () {
};
}
/**
* Write generated code to disk and return the class code
*
* {@inheritDoc}
*/
public function generate(ClassGenerator $classGenerator) : string
{
$className = trim($classGenerator->getNamespaceName(), '\\')
. '\\' . trim($classGenerator->getName(), '\\');
$generatedCode = $classGenerator->generate();
$fileName = $this->fileLocator->getProxyFileName($className);
set_error_handler($this->emptyErrorHandler);
try {
$this->writeFile("<?php\n\n" . $generatedCode, $fileName);
} catch (FileNotWritableException $fileNotWritable) {
throw $fileNotWritable;
} finally {
restore_error_handler();
}
return $generatedCode;
}
/**
* Writes the source file in such a way that race conditions are avoided when the same file is written
* multiple times in a short time period
*
* @param string $source
* @param string $location
*
* @return void
*
* @throws FileNotWritableException
*/
private function writeFile(string $source, string $location)
{
$tmpFileName = $location . '.' . uniqid('', true);
if (! file_put_contents($tmpFileName, $source)) {
throw FileNotWritableException::fromNonWritableLocation($tmpFileName);
}
if (! rename($tmpFileName, $location)) {
unlink($tmpFileName);
throw FileNotWritableException::fromInvalidMoveOperation($tmpFileName, $location);
}
}
}

View File

@@ -0,0 +1,41 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\GeneratorStrategy;
use Zend\Code\Generator\ClassGenerator;
/**
* Generator strategy interface - defines basic behavior of class generators
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface GeneratorStrategyInterface
{
/**
* Generate the provided class
*
* @param ClassGenerator $classGenerator
*
* @return string the class body
*/
public function generate(ClassGenerator $classGenerator) : string;
}

View File

@@ -0,0 +1,100 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Inflector;
use ProxyManager\Inflector\Util\ParameterHasher;
/**
* {@inheritDoc}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
final class ClassNameInflector implements ClassNameInflectorInterface
{
/**
* @var string
*/
protected $proxyNamespace;
/**
* @var int
*/
private $proxyMarkerLength;
/**
* @var string
*/
private $proxyMarker;
/**
* @var \ProxyManager\Inflector\Util\ParameterHasher
*/
private $parameterHasher;
/**
* @param string $proxyNamespace
*/
public function __construct(string $proxyNamespace)
{
$this->proxyNamespace = $proxyNamespace;
$this->proxyMarker = '\\' . static::PROXY_MARKER . '\\';
$this->proxyMarkerLength = strlen($this->proxyMarker);
$this->parameterHasher = new ParameterHasher();
}
/**
* {@inheritDoc}
*/
public function getUserClassName(string $className) : string
{
$className = ltrim($className, '\\');
if (false === $position = strrpos($className, $this->proxyMarker)) {
return $className;
}
return substr(
$className,
$this->proxyMarkerLength + $position,
strrpos($className, '\\') - ($position + $this->proxyMarkerLength)
);
}
/**
* {@inheritDoc}
*/
public function getProxyClassName(string $className, array $options = []) : string
{
return $this->proxyNamespace
. $this->proxyMarker
. $this->getUserClassName($className)
. '\\Generated' . $this->parameterHasher->hashParameters($options);
}
/**
* {@inheritDoc}
*/
public function isProxyClassName(string $className) : bool
{
return false !== strrpos($className, $this->proxyMarker);
}
}

View File

@@ -0,0 +1,63 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Inflector;
/**
* Interface for a proxy- to user-class and user- to proxy-class name inflector
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface ClassNameInflectorInterface
{
/**
* Marker for proxy classes - classes containing this marker are considered proxies
*/
const PROXY_MARKER = '__PM__';
/**
* Retrieve the class name of a user-defined class
*
* @param string $className
*
* @return string
*/
public function getUserClassName(string $className) : string;
/**
* Retrieve the class name of the proxy for the given user-defined class name
*
* @param string $className
* @param array $options arbitrary options to be used for the generated class name
*
* @return string
*/
public function getProxyClassName(string $className, array $options = []) : string;
/**
* Retrieve whether the provided class name is a proxy
*
* @param string $className
*
* @return bool
*/
public function isProxyClassName(string $className) : bool;
}

View File

@@ -0,0 +1,43 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Inflector\Util;
/**
* Encodes parameters into a class-name safe string
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class ParameterEncoder
{
/**
* Converts the given parameters into a set of characters that are safe to
* use in a class name
*
* @param array $parameters
*
* @return string
*/
public function encodeParameters(array $parameters) : string
{
return base64_encode(serialize($parameters));
}
}

View File

@@ -0,0 +1,42 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Inflector\Util;
/**
* Converts given parameters into a likely unique hash
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class ParameterHasher
{
/**
* Converts the given parameters into a likely-unique hash
*
* @param array $parameters
*
* @return string
*/
public function hashParameters(array $parameters) : string
{
return md5(serialize($parameters));
}
}

View File

@@ -0,0 +1,66 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Access interceptor object marker
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface AccessInterceptorInterface extends ProxyInterface
{
/**
* Set or remove the prefix interceptor for a method
*
* @link https://github.com/Ocramius/ProxyManager/blob/master/docs/access-interceptor-value-holder.md
*
* A prefix interceptor should have a signature like following:
*
* <code>
* $interceptor = function ($proxy, $instance, string $method, array $params, & $returnEarly) {};
* </code>
*
* @param string $methodName name of the intercepted method
* @param \Closure|null $prefixInterceptor interceptor closure or null to unset the currently active interceptor
*
* @return void
*/
public function setMethodPrefixInterceptor(string $methodName, \Closure $prefixInterceptor = null);
/**
* Set or remove the suffix interceptor for a method
*
* @link https://github.com/Ocramius/ProxyManager/blob/master/docs/access-interceptor-value-holder.md
*
* A prefix interceptor should have a signature like following:
*
* <code>
* $interceptor = function ($proxy, $instance, string $method, array $params, $returnValue, & $returnEarly) {};
* </code>
*
* @param string $methodName name of the intercepted method
* @param \Closure|null $suffixInterceptor interceptor closure or null to unset the currently active interceptor
*
* @return void
*/
public function setMethodSuffixInterceptor(string $methodName, \Closure $suffixInterceptor = null);
}

View File

@@ -0,0 +1,31 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Aggregates AccessInterceptor and ValueHolderInterface, mostly for return type hinting
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface AccessInterceptorValueHolderInterface extends AccessInterceptorInterface, ValueHolderInterface
{
}

View File

@@ -0,0 +1,33 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy\Exception;
use RuntimeException;
/**
* Remote object exception
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
class RemoteObjectException extends RuntimeException
{
}

View File

@@ -0,0 +1,31 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Fallback value holder object marker
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface FallbackValueHolderInterface extends ProxyInterface
{
}

View File

@@ -0,0 +1,31 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Ghost object marker
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface GhostObjectInterface extends LazyLoadingInterface
{
}

View File

@@ -0,0 +1,66 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Lazy loading object identifier
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface LazyLoadingInterface extends ProxyInterface
{
/**
* Set or unset the initializer for the proxy instance
*
* @link https://github.com/Ocramius/ProxyManager/blob/master/docs/lazy-loading-value-holder.md#lazy-initialization
*
* An initializer should have a signature like following:
*
* <code>
* $initializer = function (& $wrappedObject, $proxy, string $method, array $parameters, & $initializer) {};
* </code>
*
* @param \Closure|null $initializer
*
* @return mixed
*/
public function setProxyInitializer(\Closure $initializer = null);
/**
* @return \Closure|null
*/
public function getProxyInitializer();
/**
* Force initialization of the proxy
*
* @return bool true if the proxy could be initialized
*/
public function initializeProxy() : bool;
/**
* Retrieves current initialization status of the proxy
*
* @return bool
*/
public function isProxyInitialized() : bool;
}

View File

@@ -0,0 +1,31 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Null object marker
*
* @author Vincent Blanchon <blanchon.vincent@gmail.com>
* @license MIT
*/
interface NullObjectInterface extends ProxyInterface
{
}

View File

@@ -0,0 +1,31 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Base proxy marker
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface ProxyInterface
{
}

View File

@@ -0,0 +1,31 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Remote object marker
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface RemoteObjectInterface extends ProxyInterface
{
}

View File

@@ -0,0 +1,31 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Smart reference object marker
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface SmartReferenceInterface extends ProxyInterface
{
}

View File

@@ -0,0 +1,35 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Value holder marker
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface ValueHolderInterface extends ProxyInterface
{
/**
* @return object|null the wrapped value
*/
public function getWrappedValueHolderValue();
}

View File

@@ -0,0 +1,31 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Virtual Proxy - a lazy initializing object wrapping around the proxied subject
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface VirtualProxyInterface extends LazyLoadingInterface, ValueHolderInterface
{
}

View File

@@ -0,0 +1,50 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use ProxyManager\ProxyGenerator\Util\Properties;
use ProxyManager\ProxyGenerator\Util\UnsetPropertiesGenerator;
use ReflectionClass;
/**
* Magic `__wakeup` for lazy loading value holder objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicWakeup extends MagicMethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass
*/
public function __construct(ReflectionClass $originalClass)
{
parent::__construct($originalClass, '__wakeup');
$this->setBody(UnsetPropertiesGenerator::generateSnippet(
Properties::fromReflectionClass($originalClass),
'this'
));
}
}

View File

@@ -0,0 +1,55 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator;
use Closure;
use ProxyManager\Generator\MethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use Zend\Code\Generator\PropertyGenerator;
/**
* Implementation for {@see \ProxyManager\Proxy\AccessInterceptorInterface::setMethodPrefixInterceptor}
* for access interceptor objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class SetMethodPrefixInterceptor extends MethodGenerator
{
/**
* Constructor
*
* @param PropertyGenerator $prefixInterceptor
*/
public function __construct(PropertyGenerator $prefixInterceptor)
{
parent::__construct('setMethodPrefixInterceptor');
$interceptor = new ParameterGenerator('prefixInterceptor');
$interceptor->setType(Closure::class);
$interceptor->setDefaultValue(null);
$this->setParameter(new ParameterGenerator('methodName', 'string'));
$this->setParameter($interceptor);
$this->setDocblock('{@inheritDoc}');
$this->setBody('$this->' . $prefixInterceptor->getName() . '[$methodName] = $prefixInterceptor;');
}
}

View File

@@ -0,0 +1,55 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator;
use Closure;
use ProxyManager\Generator\MethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use Zend\Code\Generator\PropertyGenerator;
/**
* Implementation for {@see \ProxyManager\Proxy\AccessInterceptorInterface::setMethodSuffixInterceptor}
* for access interceptor objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class SetMethodSuffixInterceptor extends MethodGenerator
{
/**
* Constructor
*
* @param PropertyGenerator $suffixInterceptor
*/
public function __construct(PropertyGenerator $suffixInterceptor)
{
parent::__construct('setMethodSuffixInterceptor');
$interceptor = new ParameterGenerator('suffixInterceptor');
$interceptor->setType(Closure::class);
$interceptor->setDefaultValue(null);
$this->setParameter(new ParameterGenerator('methodName', 'string'));
$this->setParameter($interceptor);
$this->setDocblock('{@inheritDoc}');
$this->setBody('$this->' . $suffixInterceptor->getName() . '[$methodName] = $suffixInterceptor;');
}
}

View File

@@ -0,0 +1,45 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use Zend\Code\Generator\PropertyGenerator;
/**
* Property that contains the interceptor for operations to be executed before method execution
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MethodPrefixInterceptors extends PropertyGenerator
{
/**
* Constructor
*/
public function __construct()
{
parent::__construct(UniqueIdentifierGenerator::getIdentifier('methodPrefixInterceptors'));
$this->setDefaultValue([]);
$this->setVisibility(self::VISIBILITY_PRIVATE);
$this->setDocblock('@var \\Closure[] map of interceptors to be called per-method before execution');
}
}

View File

@@ -0,0 +1,45 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator;
use ProxyManager\Generator\Util\UniqueIdentifierGenerator;
use Zend\Code\Generator\PropertyGenerator;
/**
* Property that contains the interceptor for operations to be executed after method execution
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MethodSuffixInterceptors extends PropertyGenerator
{
/**
* Constructor
*/
public function __construct()
{
parent::__construct(UniqueIdentifierGenerator::getIdentifier('methodSuffixInterceptors'));
$this->setDefaultValue([]);
$this->setVisibility(self::VISIBILITY_PRIVATE);
$this->setDocblock('@var \\Closure[] map of interceptors to be called per-method after execution');
}
}

View File

@@ -0,0 +1,89 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use ProxyManager\ProxyGenerator\Util\Properties;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* The `bindProxyProperties` method implementation for access interceptor scope localizers
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class BindProxyProperties extends MethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct(
'bindProxyProperties',
[
new ParameterGenerator('localizedObject', $originalClass->getName()),
new ParameterGenerator('prefixInterceptors', 'array', []),
new ParameterGenerator('suffixInterceptors', 'array', []),
],
static::FLAG_PRIVATE,
null,
"@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"
);
$localizedProperties = [];
$properties = Properties::fromReflectionClass($originalClass);
foreach ($properties->getAccessibleProperties() as $property) {
$propertyName = $property->getName();
$localizedProperties[] = '$this->' . $propertyName . ' = & $localizedObject->' . $propertyName . ";";
}
foreach ($properties->getPrivateProperties() as $property) {
$propertyName = $property->getName();
$localizedProperties[] = "\\Closure::bind(function () use (\$localizedObject) {\n "
. '$this->' . $propertyName . ' = & $localizedObject->' . $propertyName . ";\n"
. '}, $this, ' . var_export($property->getDeclaringClass()->getName(), true)
. ')->__invoke();';
}
$this->setBody(
(empty($localizedProperties) ? '' : implode("\n\n", $localizedProperties) . "\n\n")
. '$this->' . $prefixInterceptors->getName() . " = \$prefixInterceptors;\n"
. '$this->' . $suffixInterceptors->getName() . " = \$suffixInterceptors;"
);
}
}

View File

@@ -0,0 +1,69 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util\InterceptorGenerator;
use Zend\Code\Generator\PropertyGenerator;
use Zend\Code\Reflection\MethodReflection;
/**
* Method with additional pre- and post- interceptor logic in the body
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class InterceptedMethod extends MethodGenerator
{
/**
* @param \Zend\Code\Reflection\MethodReflection $originalMethod
* @param \Zend\Code\Generator\PropertyGenerator $prefixInterceptors
* @param \Zend\Code\Generator\PropertyGenerator $suffixInterceptors
*
* @return self
*/
public static function generateMethod(
MethodReflection $originalMethod,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) : self {
/* @var $method self */
$method = static::fromReflection($originalMethod);
$forwardedParams = [];
foreach ($originalMethod->getParameters() as $parameter) {
$forwardedParams[] = ($parameter->isVariadic() ? '...' : '') . '$' . $parameter->getName();
}
$method->setDocblock('{@inheritDoc}');
$method->setBody(
InterceptorGenerator::createInterceptedMethodBody(
'$returnValue = parent::'
. $originalMethod->getName() . '(' . implode(', ', $forwardedParams) . ');',
$method,
$prefixInterceptors,
$suffixInterceptors
)
);
return $method;
}
}

View File

@@ -0,0 +1,59 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util\InterceptorGenerator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__clone` for lazy loading ghost objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicClone extends MagicMethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct($originalClass, '__clone');
$this->setBody(
InterceptorGenerator::createInterceptedMethodBody(
$originalClass->hasMethod('__clone') ? '$returnValue = parent::__clone();' : '$returnValue = null;',
$this,
$prefixInterceptors,
$suffixInterceptors
)
);
}
}

View File

@@ -0,0 +1,75 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util\InterceptorGenerator;
use ProxyManager\ProxyGenerator\Util\PublicScopeSimulator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__get` for lazy loading ghost objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicGet extends MagicMethodGenerator
{
/**
* @param ReflectionClass $originalClass
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct($originalClass, '__get', [new ParameterGenerator('name')]);
$override = $originalClass->hasMethod('__get');
$this->setDocblock(($override ? "{@inheritDoc}\n" : '') . '@param string $name');
if ($override) {
$callParent = '$returnValue = & parent::__get($name);';
} else {
$callParent = PublicScopeSimulator::getPublicAccessSimulationCode(
PublicScopeSimulator::OPERATION_GET,
'name',
null,
null,
'returnValue'
);
}
$this->setBody(
InterceptorGenerator::createInterceptedMethodBody(
$callParent,
$this,
$prefixInterceptors,
$suffixInterceptors
)
);
}
}

View File

@@ -0,0 +1,75 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util\InterceptorGenerator;
use ProxyManager\ProxyGenerator\Util\PublicScopeSimulator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__isset` method for lazy loading ghost objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicIsset extends MagicMethodGenerator
{
/**
* @param ReflectionClass $originalClass
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct($originalClass, '__isset', [new ParameterGenerator('name')]);
$override = $originalClass->hasMethod('__isset');
$this->setDocblock(($override ? "{@inheritDoc}\n" : '') . '@param string $name');
if ($override) {
$callParent = '$returnValue = & parent::__isset($name);';
} else {
$callParent = PublicScopeSimulator::getPublicAccessSimulationCode(
PublicScopeSimulator::OPERATION_ISSET,
'name',
null,
null,
'returnValue'
);
}
$this->setBody(
InterceptorGenerator::createInterceptedMethodBody(
$callParent,
$this,
$prefixInterceptors,
$suffixInterceptors
)
);
}
}

View File

@@ -0,0 +1,79 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util\InterceptorGenerator;
use ProxyManager\ProxyGenerator\Util\PublicScopeSimulator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__set` for lazy loading ghost objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicSet extends MagicMethodGenerator
{
/**
* @param \ReflectionClass $originalClass
* @param \Zend\Code\Generator\PropertyGenerator $prefixInterceptors
* @param \Zend\Code\Generator\PropertyGenerator $suffixInterceptors
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct(
$originalClass,
'__set',
[new ParameterGenerator('name'), new ParameterGenerator('value')]
);
$override = $originalClass->hasMethod('__set');
$this->setDocblock(($override ? "{@inheritDoc}\n" : '') . '@param string $name');
if ($override) {
$callParent = '$returnValue = & parent::__set($name, $value);';
} else {
$callParent = PublicScopeSimulator::getPublicAccessSimulationCode(
PublicScopeSimulator::OPERATION_SET,
'name',
'value',
null,
'returnValue'
);
}
$this->setBody(
InterceptorGenerator::createInterceptedMethodBody(
$callParent,
$this,
$prefixInterceptors,
$suffixInterceptors
)
);
}
}

View File

@@ -0,0 +1,63 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util\InterceptorGenerator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__sleep` for lazy loading ghost objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicSleep extends MagicMethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct($originalClass, '__sleep');
$callParent = $originalClass->hasMethod('__sleep')
? '$returnValue = & parent::__sleep();'
: '$returnValue = array_keys((array) $this);';
$this->setBody(
InterceptorGenerator::createInterceptedMethodBody(
$callParent,
$this,
$prefixInterceptors,
$suffixInterceptors
)
);
}
}

View File

@@ -0,0 +1,75 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util\InterceptorGenerator;
use ProxyManager\ProxyGenerator\Util\PublicScopeSimulator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__unset` method for lazy loading ghost objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicUnset extends MagicMethodGenerator
{
/**
* @param ReflectionClass $originalClass
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct($originalClass, '__unset', [new ParameterGenerator('name')]);
$override = $originalClass->hasMethod('__unset');
$this->setDocblock(($override ? "{@inheritDoc}\n" : '') . '@param string $name');
if ($override) {
$callParent = '$returnValue = & parent::__unset($name);';
} else {
$callParent = PublicScopeSimulator::getPublicAccessSimulationCode(
PublicScopeSimulator::OPERATION_UNSET,
'name',
null,
null,
'returnValue'
);
}
$this->setBody(
InterceptorGenerator::createInterceptedMethodBody(
$callParent,
$this,
$prefixInterceptors,
$suffixInterceptors
)
);
}
}

View File

@@ -0,0 +1,74 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use ReflectionClass;
/**
* The `staticProxyConstructor` implementation for an access interceptor scope localizer proxy
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class StaticProxyConstructor extends MethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass
*/
public function __construct(ReflectionClass $originalClass)
{
parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC);
$localizedObject = new ParameterGenerator('localizedObject');
$prefix = new ParameterGenerator('prefixInterceptors');
$suffix = new ParameterGenerator('suffixInterceptors');
$localizedObject->setType($originalClass->getName());
$prefix->setDefaultValue([]);
$suffix->setDefaultValue([]);
$prefix->setType('array');
$suffix->setType('array');
$this->setParameter($localizedObject);
$this->setParameter($prefix);
$this->setParameter($suffix);
$this->setReturnType($originalClass->getName());
$this->setDocblock(
"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\n\n"
. "@return self"
);
$this->setBody(
'static $reflection;' . "\n\n"
. '$reflection = $reflection ?: $reflection = new \ReflectionClass(__CLASS__);' . "\n"
. '$instance = $reflection->newInstanceWithoutConstructor();' . "\n\n"
. '$instance->bindProxyProperties($localizedObject, $prefixInterceptors, $suffixInterceptors);' . "\n\n"
. 'return $instance;'
);
}
}

View File

@@ -0,0 +1,83 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\Util;
use ProxyManager\Generator\MethodGenerator;
use Zend\Code\Generator\PropertyGenerator;
/**
* Utility to create pre- and post- method interceptors around a given method body
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @private - this class is just here as a small utility for this component, don't use it in your own code
*/
class InterceptorGenerator
{
/**
* @param string $methodBody the body of the previously generated code.
* It MUST assign the return value to a variable
* `$returnValue` instead of directly returning
* @param \ProxyManager\Generator\MethodGenerator $method
* @param \Zend\Code\Generator\PropertyGenerator $prefixInterceptors
* @param \Zend\Code\Generator\PropertyGenerator $suffixInterceptors
*
* @return string
*/
public static function createInterceptedMethodBody(
string $methodBody,
MethodGenerator $method,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) : string {
$name = var_export($method->getName(), true);
$prefixInterceptors = $prefixInterceptors->getName();
$suffixInterceptors = $suffixInterceptors->getName();
$params = [];
foreach ($method->getParameters() as $parameter) {
$parameterName = $parameter->getName();
$params[] = var_export($parameterName, true) . ' => $' . $parameter->getName();
}
$paramsString = 'array(' . implode(', ', $params) . ')';
return "if (isset(\$this->$prefixInterceptors" . "[$name])) {\n"
. " \$returnEarly = false;\n"
. " \$prefixReturnValue = \$this->$prefixInterceptors" . "[$name]->__invoke("
. "\$this, \$this, $name, $paramsString, \$returnEarly);\n\n"
. " if (\$returnEarly) {\n"
. " return \$prefixReturnValue;\n"
. " }\n"
. "}\n\n"
. $methodBody . "\n\n"
. "if (isset(\$this->$suffixInterceptors" . "[$name])) {\n"
. " \$returnEarly = false;\n"
. " \$suffixReturnValue = \$this->$suffixInterceptors" . "[$name]->__invoke("
. "\$this, \$this, $name, $paramsString, \$returnValue, \$returnEarly);\n\n"
. " if (\$returnEarly) {\n"
. " return \$suffixReturnValue;\n"
. " }\n"
. "}\n\n"
. "return \$returnValue;";
}
}

View File

@@ -0,0 +1,109 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator;
use ProxyManager\Generator\Util\ClassGeneratorUtils;
use ProxyManager\Proxy\AccessInterceptorInterface;
use ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\SetMethodPrefixInterceptor;
use ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\SetMethodSuffixInterceptor;
use ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator\MethodPrefixInterceptors;
use ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator\MethodSuffixInterceptors;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\BindProxyProperties;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\InterceptedMethod;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicClone;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicGet;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicIsset;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicSet;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicSleep;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\MagicUnset;
use ProxyManager\ProxyGenerator\AccessInterceptorScopeLocalizer\MethodGenerator\StaticProxyConstructor;
use ProxyManager\ProxyGenerator\Assertion\CanProxyAssertion;
use ProxyManager\ProxyGenerator\Util\ProxiedMethodsFilter;
use ReflectionClass;
use ReflectionMethod;
use Zend\Code\Generator\ClassGenerator;
use Zend\Code\Generator\MethodGenerator;
use Zend\Code\Reflection\MethodReflection;
/**
* Generator for proxies implementing {@see \ProxyManager\Proxy\ValueHolderInterface}
* and localizing scope of the proxied object at instantiation
*
* {@inheritDoc}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class AccessInterceptorScopeLocalizerGenerator implements ProxyGeneratorInterface
{
/**
* {@inheritDoc}
*/
public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
{
CanProxyAssertion::assertClassCanBeProxied($originalClass, false);
$classGenerator->setExtendedClass($originalClass->getName());
$classGenerator->setImplementedInterfaces([AccessInterceptorInterface::class]);
$classGenerator->addPropertyFromGenerator($prefixInterceptors = new MethodPrefixInterceptors());
$classGenerator->addPropertyFromGenerator($suffixInterceptors = new MethodSuffixInterceptors());
array_map(
function (MethodGenerator $generatedMethod) use ($originalClass, $classGenerator) {
ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod);
},
array_merge(
array_map(
$this->buildMethodInterceptor($prefixInterceptors, $suffixInterceptors),
ProxiedMethodsFilter::getProxiedMethods(
$originalClass,
['__get', '__set', '__isset', '__unset', '__clone', '__sleep']
)
),
[
new StaticProxyConstructor($originalClass, $prefixInterceptors, $suffixInterceptors),
new BindProxyProperties($originalClass, $prefixInterceptors, $suffixInterceptors),
new SetMethodPrefixInterceptor($prefixInterceptors),
new SetMethodSuffixInterceptor($suffixInterceptors),
new MagicGet($originalClass, $prefixInterceptors, $suffixInterceptors),
new MagicSet($originalClass, $prefixInterceptors, $suffixInterceptors),
new MagicIsset($originalClass, $prefixInterceptors, $suffixInterceptors),
new MagicUnset($originalClass, $prefixInterceptors, $suffixInterceptors),
new MagicSleep($originalClass, $prefixInterceptors, $suffixInterceptors),
new MagicClone($originalClass, $prefixInterceptors, $suffixInterceptors),
]
)
);
}
private function buildMethodInterceptor(
MethodPrefixInterceptors $prefixInterceptors,
MethodSuffixInterceptors $suffixInterceptors
) : callable {
return function (ReflectionMethod $method) use ($prefixInterceptors, $suffixInterceptors) : InterceptedMethod {
return InterceptedMethod::generateMethod(
new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()),
$prefixInterceptors,
$suffixInterceptors
);
};
}
}

View File

@@ -0,0 +1,72 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\Util\InterceptorGenerator;
use Zend\Code\Generator\PropertyGenerator;
use Zend\Code\Reflection\MethodReflection;
/**
* Method with additional pre- and post- interceptor logic in the body
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class InterceptedMethod extends MethodGenerator
{
/**
* @param \Zend\Code\Reflection\MethodReflection $originalMethod
* @param \Zend\Code\Generator\PropertyGenerator $valueHolderProperty
* @param \Zend\Code\Generator\PropertyGenerator $prefixInterceptors
* @param \Zend\Code\Generator\PropertyGenerator $suffixInterceptors
*
* @return self
*/
public static function generateMethod(
MethodReflection $originalMethod,
PropertyGenerator $valueHolderProperty,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) : self {
/* @var $method self */
$method = static::fromReflection($originalMethod);
$forwardedParams = [];
foreach ($originalMethod->getParameters() as $parameter) {
$forwardedParams[] = ($parameter->isVariadic() ? '...' : '') . '$' . $parameter->getName();
}
$method->setDocblock('{@inheritDoc}');
$method->setBody(
InterceptorGenerator::createInterceptedMethodBody(
'$returnValue = $this->' . $valueHolderProperty->getName() . '->'
. $originalMethod->getName() . '(' . implode(', ', $forwardedParams) . ');',
$method,
$valueHolderProperty,
$prefixInterceptors,
$suffixInterceptors
)
);
return $method;
}
}

View File

@@ -0,0 +1,65 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__clone` for lazy loading value holder objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicClone extends MagicMethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass
* @param PropertyGenerator $valueHolderProperty
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $valueHolderProperty,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct($originalClass, '__clone');
$valueHolder = $valueHolderProperty->getName();
$prefix = $prefixInterceptors->getName();
$suffix = $suffixInterceptors->getName();
$this->setBody(
"\$this->$valueHolder = clone \$this->$valueHolder;\n\n"
. "foreach (\$this->$prefix as \$key => \$value) {\n"
. " \$this->$prefix" . "[\$key] = clone \$value;\n"
. "}\n\n"
. "foreach (\$this->$suffix as \$key => \$value) {\n"
. " \$this->$suffix" . "[\$key] = clone \$value;\n"
. "}"
);
}
}

View File

@@ -0,0 +1,86 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\Util\InterceptorGenerator;
use ProxyManager\ProxyGenerator\PropertyGenerator\PublicPropertiesMap;
use ProxyManager\ProxyGenerator\Util\PublicScopeSimulator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__get` for method interceptor value holder objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicGet extends MagicMethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass
* @param PropertyGenerator $valueHolder
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
* @param PublicPropertiesMap $publicProperties
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $valueHolder,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors,
PublicPropertiesMap $publicProperties
) {
parent::__construct($originalClass, '__get', [new ParameterGenerator('name')]);
$override = $originalClass->hasMethod('__get');
$valueHolderName = $valueHolder->getName();
$this->setDocblock(($override ? "{@inheritDoc}\n" : '') . '@param string $name');
$callParent = PublicScopeSimulator::getPublicAccessSimulationCode(
PublicScopeSimulator::OPERATION_GET,
'name',
'value',
$valueHolder,
'returnValue'
);
if (! $publicProperties->isEmpty()) {
$callParent = 'if (isset(self::$' . $publicProperties->getName() . "[\$name])) {\n"
. ' $returnValue = & $this->' . $valueHolderName . '->$name;'
. "\n} else {\n $callParent\n}\n\n";
}
$this->setBody(
InterceptorGenerator::createInterceptedMethodBody(
$callParent,
$this,
$valueHolder,
$prefixInterceptors,
$suffixInterceptors
)
);
}
}

View File

@@ -0,0 +1,85 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\Util\InterceptorGenerator;
use ProxyManager\ProxyGenerator\PropertyGenerator\PublicPropertiesMap;
use ProxyManager\ProxyGenerator\Util\PublicScopeSimulator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__isset` for method interceptor value holder objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicIsset extends MagicMethodGenerator
{
/**
* Constructor
* @param ReflectionClass $originalClass
* @param PropertyGenerator $valueHolder
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
* @param PublicPropertiesMap $publicProperties
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $valueHolder,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors,
PublicPropertiesMap $publicProperties
) {
parent::__construct($originalClass, '__isset', [new ParameterGenerator('name')]);
$override = $originalClass->hasMethod('__isset');
$valueHolderName = $valueHolder->getName();
$this->setDocblock(($override ? "{@inheritDoc}\n" : '') . '@param string $name');
$callParent = PublicScopeSimulator::getPublicAccessSimulationCode(
PublicScopeSimulator::OPERATION_ISSET,
'name',
'value',
$valueHolder,
'returnValue'
);
if (! $publicProperties->isEmpty()) {
$callParent = 'if (isset(self::$' . $publicProperties->getName() . "[\$name])) {\n"
. ' $returnValue = isset($this->' . $valueHolderName . '->$name);'
. "\n} else {\n $callParent\n}\n\n";
}
$this->setBody(
InterceptorGenerator::createInterceptedMethodBody(
$callParent,
$this,
$valueHolder,
$prefixInterceptors,
$suffixInterceptors
)
);
}
}

View File

@@ -0,0 +1,89 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\Util\InterceptorGenerator;
use ProxyManager\ProxyGenerator\PropertyGenerator\PublicPropertiesMap;
use ProxyManager\ProxyGenerator\Util\PublicScopeSimulator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__set` for method interceptor value holder objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicSet extends MagicMethodGenerator
{
/**
* Constructor
* @param ReflectionClass $originalClass
* @param PropertyGenerator $valueHolder
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
* @param PublicPropertiesMap $publicProperties
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $valueHolder,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors,
PublicPropertiesMap $publicProperties
) {
parent::__construct(
$originalClass,
'__set',
[new ParameterGenerator('name'), new ParameterGenerator('value')]
);
$override = $originalClass->hasMethod('__set');
$valueHolderName = $valueHolder->getName();
$this->setDocblock(($override ? "{@inheritDoc}\n" : '') . '@param string $name');
$callParent = PublicScopeSimulator::getPublicAccessSimulationCode(
PublicScopeSimulator::OPERATION_SET,
'name',
'value',
$valueHolder,
'returnValue'
);
if (! $publicProperties->isEmpty()) {
$callParent = 'if (isset(self::$' . $publicProperties->getName() . "[\$name])) {\n"
. ' $returnValue = ($this->' . $valueHolderName . '->$name = $value);'
. "\n} else {\n $callParent\n}\n\n";
}
$this->setBody(
InterceptorGenerator::createInterceptedMethodBody(
$callParent,
$this,
$valueHolder,
$prefixInterceptors,
$suffixInterceptors
)
);
}
}

View File

@@ -0,0 +1,87 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator;
use ProxyManager\Generator\MagicMethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\Util\InterceptorGenerator;
use ProxyManager\ProxyGenerator\PropertyGenerator\PublicPropertiesMap;
use ProxyManager\ProxyGenerator\Util\PublicScopeSimulator;
use ReflectionClass;
use Zend\Code\Generator\PropertyGenerator;
/**
* Magic `__unset` for method interceptor value holder objects
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class MagicUnset extends MagicMethodGenerator
{
/**
* Constructor
* @param ReflectionClass $originalClass
* @param PropertyGenerator $valueHolder
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
* @param PublicPropertiesMap $publicProperties
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $valueHolder,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors,
PublicPropertiesMap $publicProperties
) {
parent::__construct($originalClass, '__unset', [new ParameterGenerator('name')]);
$override = $originalClass->hasMethod('__unset');
$valueHolderName = $valueHolder->getName();
$this->setDocblock(($override ? "{@inheritDoc}\n" : '') . '@param string $name');
$callParent = PublicScopeSimulator::getPublicAccessSimulationCode(
PublicScopeSimulator::OPERATION_UNSET,
'name',
'value',
$valueHolder,
'returnValue'
);
if (! $publicProperties->isEmpty()) {
$callParent = 'if (isset(self::$' . $publicProperties->getName() . "[\$name])) {\n"
. ' unset($this->' . $valueHolderName . '->$name);'
. "\n} else {\n $callParent\n}\n\n";
}
$callParent .= '$returnValue = false;';
$this->setBody(
InterceptorGenerator::createInterceptedMethodBody(
$callParent,
$this,
$valueHolder,
$prefixInterceptors,
$suffixInterceptors
)
);
}
}

View File

@@ -0,0 +1,86 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\ProxyGenerator\Util\Properties;
use ProxyManager\ProxyGenerator\Util\UnsetPropertiesGenerator;
use ReflectionClass;
use Zend\Code\Generator\ParameterGenerator;
use Zend\Code\Generator\PropertyGenerator;
/**
* The `staticProxyConstructor` implementation for access interceptor value holders
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class StaticProxyConstructor extends MethodGenerator
{
/**
* Constructor
*
* @param ReflectionClass $originalClass
* @param PropertyGenerator $valueHolder
* @param PropertyGenerator $prefixInterceptors
* @param PropertyGenerator $suffixInterceptors
*/
public function __construct(
ReflectionClass $originalClass,
PropertyGenerator $valueHolder,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) {
parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC);
$prefix = new ParameterGenerator('prefixInterceptors');
$suffix = new ParameterGenerator('suffixInterceptors');
$prefix->setDefaultValue([]);
$suffix->setDefaultValue([]);
$prefix->setType('array');
$suffix->setType('array');
$this->setParameter(new ParameterGenerator('wrappedObject'));
$this->setParameter($prefix);
$this->setParameter($suffix);
$this->setReturnType($originalClass->getName());
$this->setDocblock(
"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\n\n"
. "@return self"
);
$this->setBody(
'static $reflection;' . "\n\n"
. '$reflection = $reflection ?: $reflection = new \ReflectionClass(__CLASS__);' . "\n"
. '$instance = (new \ReflectionClass(get_class()))->newInstanceWithoutConstructor();' . "\n\n"
. UnsetPropertiesGenerator::generateSnippet(Properties::fromReflectionClass($originalClass), 'instance')
. '$instance->' . $valueHolder->getName() . " = \$wrappedObject;\n"
. '$instance->' . $prefixInterceptors->getName() . " = \$prefixInterceptors;\n"
. '$instance->' . $suffixInterceptors->getName() . " = \$suffixInterceptors;\n\n"
. 'return $instance;'
);
}
}

View File

@@ -0,0 +1,86 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\Util;
use ProxyManager\Generator\MethodGenerator;
use Zend\Code\Generator\PropertyGenerator;
/**
* Utility to create pre- and post- method interceptors around a given method body
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*
* @private - this class is just here as a small utility for this component, don't use it in your own code
*/
class InterceptorGenerator
{
/**
* @param string $methodBody the body of the previously generated code.
* It MUST assign the return value to a variable
* `$returnValue` instead of directly returning
* @param \ProxyManager\Generator\MethodGenerator $method
* @param \Zend\Code\Generator\PropertyGenerator $valueHolder
* @param \Zend\Code\Generator\PropertyGenerator $prefixInterceptors
* @param \Zend\Code\Generator\PropertyGenerator $suffixInterceptors
*
* @return string
*/
public static function createInterceptedMethodBody(
string $methodBody,
MethodGenerator $method,
PropertyGenerator $valueHolder,
PropertyGenerator $prefixInterceptors,
PropertyGenerator $suffixInterceptors
) : string {
$name = var_export($method->getName(), true);
$valueHolder = $valueHolder->getName();
$prefixInterceptors = $prefixInterceptors->getName();
$suffixInterceptors = $suffixInterceptors->getName();
$params = [];
foreach ($method->getParameters() as $parameter) {
$parameterName = $parameter->getName();
$params[] = var_export($parameterName, true) . ' => $' . $parameter->getName();
}
$paramsString = 'array(' . implode(', ', $params) . ')';
return "if (isset(\$this->$prefixInterceptors" . "[$name])) {\n"
. " \$returnEarly = false;\n"
. " \$prefixReturnValue = \$this->$prefixInterceptors" . "[$name]->__invoke("
. "\$this, \$this->$valueHolder, $name, $paramsString, \$returnEarly);\n\n"
. " if (\$returnEarly) {\n"
. " return \$prefixReturnValue;\n"
. " }\n"
. "}\n\n"
. $methodBody . "\n\n"
. "if (isset(\$this->$suffixInterceptors" . "[$name])) {\n"
. " \$returnEarly = false;\n"
. " \$suffixReturnValue = \$this->$suffixInterceptors" . "[$name]->__invoke("
. "\$this, \$this->$valueHolder, $name, $paramsString, \$returnValue, \$returnEarly);\n\n"
. " if (\$returnEarly) {\n"
. " return \$suffixReturnValue;\n"
. " }\n"
. "}\n\n"
. "return \$returnValue;";
}
}

View File

@@ -0,0 +1,149 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator;
use ProxyManager\Generator\Util\ClassGeneratorUtils;
use ProxyManager\Proxy\AccessInterceptorValueHolderInterface;
use ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\MagicWakeup;
use ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\SetMethodPrefixInterceptor;
use ProxyManager\ProxyGenerator\AccessInterceptor\MethodGenerator\SetMethodSuffixInterceptor;
use ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator\MethodPrefixInterceptors;
use ProxyManager\ProxyGenerator\AccessInterceptor\PropertyGenerator\MethodSuffixInterceptors;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\InterceptedMethod;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\MagicClone;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\MagicGet;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\MagicIsset;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\MagicSet;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\MagicUnset;
use ProxyManager\ProxyGenerator\AccessInterceptorValueHolder\MethodGenerator\StaticProxyConstructor;
use ProxyManager\ProxyGenerator\Assertion\CanProxyAssertion;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolder\PropertyGenerator\ValueHolderProperty;
use ProxyManager\ProxyGenerator\PropertyGenerator\PublicPropertiesMap;
use ProxyManager\ProxyGenerator\Util\Properties;
use ProxyManager\ProxyGenerator\Util\ProxiedMethodsFilter;
use ProxyManager\ProxyGenerator\ValueHolder\MethodGenerator\Constructor;
use ProxyManager\ProxyGenerator\ValueHolder\MethodGenerator\GetWrappedValueHolderValue;
use ProxyManager\ProxyGenerator\ValueHolder\MethodGenerator\MagicSleep;
use ReflectionClass;
use ReflectionMethod;
use Zend\Code\Generator\ClassGenerator;
use Zend\Code\Generator\MethodGenerator;
use Zend\Code\Reflection\MethodReflection;
/**
* Generator for proxies implementing {@see \ProxyManager\Proxy\ValueHolderInterface}
* and {@see \ProxyManager\Proxy\AccessInterceptorInterface}
*
* {@inheritDoc}
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
class AccessInterceptorValueHolderGenerator implements ProxyGeneratorInterface
{
/**
* {@inheritDoc}
*/
public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
{
CanProxyAssertion::assertClassCanBeProxied($originalClass);
$publicProperties = new PublicPropertiesMap(Properties::fromReflectionClass($originalClass));
$interfaces = [AccessInterceptorValueHolderInterface::class];
if ($originalClass->isInterface()) {
$interfaces[] = $originalClass->getName();
} else {
$classGenerator->setExtendedClass($originalClass->getName());
}
$classGenerator->setImplementedInterfaces($interfaces);
$classGenerator->addPropertyFromGenerator($valueHolder = new ValueHolderProperty());
$classGenerator->addPropertyFromGenerator($prefixInterceptors = new MethodPrefixInterceptors());
$classGenerator->addPropertyFromGenerator($suffixInterceptors = new MethodSuffixInterceptors());
$classGenerator->addPropertyFromGenerator($publicProperties);
array_map(
function (MethodGenerator $generatedMethod) use ($originalClass, $classGenerator) {
ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod);
},
array_merge(
array_map(
$this->buildMethodInterceptor($prefixInterceptors, $suffixInterceptors, $valueHolder),
ProxiedMethodsFilter::getProxiedMethods($originalClass)
),
[
Constructor::generateMethod($originalClass, $valueHolder),
new StaticProxyConstructor($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors),
new GetWrappedValueHolderValue($valueHolder),
new SetMethodPrefixInterceptor($prefixInterceptors),
new SetMethodSuffixInterceptor($suffixInterceptors),
new MagicGet(
$originalClass,
$valueHolder,
$prefixInterceptors,
$suffixInterceptors,
$publicProperties
),
new MagicSet(
$originalClass,
$valueHolder,
$prefixInterceptors,
$suffixInterceptors,
$publicProperties
),
new MagicIsset(
$originalClass,
$valueHolder,
$prefixInterceptors,
$suffixInterceptors,
$publicProperties
),
new MagicUnset(
$originalClass,
$valueHolder,
$prefixInterceptors,
$suffixInterceptors,
$publicProperties
),
new MagicClone($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors),
new MagicSleep($originalClass, $valueHolder),
new MagicWakeup($originalClass, $valueHolder),
]
)
);
}
private function buildMethodInterceptor(
MethodPrefixInterceptors $prefixes,
MethodSuffixInterceptors $suffixes,
ValueHolderProperty $valueHolder
) : callable {
return function (ReflectionMethod $method) use ($prefixes, $suffixes, $valueHolder) : InterceptedMethod {
return InterceptedMethod::generateMethod(
new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()),
$valueHolder,
$prefixes,
$suffixes
);
};
}
}

View File

@@ -0,0 +1,112 @@
<?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.
*/
declare(strict_types=1);
namespace ProxyManager\ProxyGenerator\Assertion;
use BadMethodCallException;
use ProxyManager\Exception\InvalidProxiedClassException;
use ReflectionClass;
use ReflectionMethod;
/**
* Assertion that verifies that a class can be proxied
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
final class CanProxyAssertion
{
/**
* Disabled constructor: not meant to be instantiated
*
* @throws BadMethodCallException
*/
public function __construct()
{
throw new BadMethodCallException('Unsupported constructor.');
}
/**
* @param ReflectionClass $originalClass
* @param bool $allowInterfaces
*
* @return void
*
* @throws InvalidProxiedClassException
*/
public static function assertClassCanBeProxied(ReflectionClass $originalClass, bool $allowInterfaces = true)
{
self::isNotFinal($originalClass);
self::hasNoAbstractProtectedMethods($originalClass);
if (! $allowInterfaces) {
self::isNotInterface($originalClass);
}
}
/**
* @param ReflectionClass $originalClass
*
* @return void
*
* @throws InvalidProxiedClassException
*/
private static function isNotFinal(ReflectionClass $originalClass)
{
if ($originalClass->isFinal()) {
throw InvalidProxiedClassException::finalClassNotSupported($originalClass);
}
}
/**
* @param ReflectionClass $originalClass
*
* @return void
*
* @throws InvalidProxiedClassException
*/
private static function hasNoAbstractProtectedMethods(ReflectionClass $originalClass)
{
$protectedAbstract = array_filter(
$originalClass->getMethods(),
function (ReflectionMethod $method) : bool {
return $method->isAbstract() && $method->isProtected();
}
);
if ($protectedAbstract) {
throw InvalidProxiedClassException::abstractProtectedMethodsNotSupported($originalClass);
}
}
/**
* @param ReflectionClass $originalClass
*
* @return void
*
* @throws InvalidProxiedClassException
*/
private static function isNotInterface(ReflectionClass $originalClass)
{
if ($originalClass->isInterface()) {
throw InvalidProxiedClassException::interfaceNotSupported($originalClass);
}
}
}

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