Created
May 29, 2018 18:24
-
-
Save RemiCollin/94f85145b92656d0d83fbedd0d04be8c to your computer and use it in GitHub Desktop.
Generate adapters for single action classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Logger; | |
use Log; | |
use ProxyManager\Factory\AccessInterceptorValueHolderFactory as Factory; | |
use Illuminate\Contracts\Container\Container; | |
class ActionLoggerGenerator | |
{ | |
protected $container; | |
public function __construct(Container $container) | |
{ | |
$this->container = $container; | |
} | |
/** | |
* Generate proxies and bind them inside the container | |
* | |
* @param array $actions an array containing action classes to generate proxy for | |
* @return void | |
*/ | |
public function generate(array $actions) | |
{ | |
array_map(function($action) { | |
$this->container->bind($action, function($app) use($action) { | |
return $this->generateProxy($action); | |
}); | |
}, $actions); | |
} | |
protected function generateProxy(string $class) | |
{ | |
// In order to create the proxy, we need to build the actual's | |
// class instance. We're using the laravel's container for this | |
// job, so any dependency it needs will be injected. | |
$actionInstance = $this->container->build($class); | |
$proxyFactory = new Factory(); | |
$proxy = $factory->createProxy($actionInstance); | |
// We create an anonymous function that will simply log the User's id and the | |
// class name of the executed action class. This function will be call with a bunch | |
// of useful parameters, as the original object instance, the parameters that are passed | |
// to the method, and the return value, for the most useful ones. | |
$postExecuteInterceptor = function ($proxy, $instance, $method, $params, $returnValue, & $returnEarly) { | |
$userId = auth()->user()->id; | |
Log::info("User $id . Action ".get_class($instance)); | |
}; | |
// We tell the proxy to run this function after the execute() method has | |
// been called. We could have use `setMethodPrefixInterceptor` if we had wanted | |
// to run the function before the method is called. | |
$proxy->setMethodSuffixInterceptor('execute', $postExecuteInterceptor); | |
return $proxy; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment