|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of php-cache\cache-bundle package. |
| 5 | + * |
| 6 | + * (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com> |
| 7 | + * |
| 8 | + * This source file is subject to the MIT license that is bundled |
| 9 | + * with this source code in the file LICENSE. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Cache\CacheBundle\DataCollector; |
| 13 | + |
| 14 | +/** |
| 15 | + * Generate proxies over your cache pool. This should only be used in development. |
| 16 | + * |
| 17 | + * @author Tobias Nyholm <tobias.nyholm@gmail.com> |
| 18 | + */ |
| 19 | +class ProxyFactory |
| 20 | +{ |
| 21 | + /** |
| 22 | + * @type string |
| 23 | + */ |
| 24 | + private $proxyDirectory; |
| 25 | + |
| 26 | + /** |
| 27 | + * @param string $proxyDirectory |
| 28 | + */ |
| 29 | + public function __construct($proxyDirectory) |
| 30 | + { |
| 31 | + $this->proxyDirectory = $proxyDirectory; |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Create a proxy that handles data collecting better. |
| 36 | + * |
| 37 | + * @param string $class |
| 38 | + * @param string &$proxyFile where we store the proxy class |
| 39 | + * |
| 40 | + * @return string the name of a much much better class |
| 41 | + */ |
| 42 | + public function createProxy($class, &$proxyFile = null) |
| 43 | + { |
| 44 | + $proxyClass = $this->getProxyClass($class); |
| 45 | + $class = '\\'.rtrim($class, '\\'); |
| 46 | + $proxyFile = $this->proxyDirectory.'/'.$proxyClass.'.php'; |
| 47 | + |
| 48 | + if (class_exists($proxyClass)) { |
| 49 | + return $proxyClass; |
| 50 | + } |
| 51 | + |
| 52 | + $content = file_get_contents(dirname(__DIR__).'/Resources/proxy/template.php'); |
| 53 | + $content = str_replace('__TPL_CLASS__', $proxyClass, $content); |
| 54 | + $content = str_replace('__TPL_EXTENDS__', $class, $content); |
| 55 | + |
| 56 | + $this->checkProxyDirectory(); |
| 57 | + file_put_contents($proxyFile, $content); |
| 58 | + require $proxyFile; |
| 59 | + |
| 60 | + return $proxyClass; |
| 61 | + } |
| 62 | + |
| 63 | + private function checkProxyDirectory() |
| 64 | + { |
| 65 | + if (!is_dir($this->proxyDirectory)) { |
| 66 | + @mkdir($this->proxyDirectory, 0777, true); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private function getProxyClass($namespace) |
| 71 | + { |
| 72 | + return 'php_cache_proxy_'.str_replace('\\', '_', $namespace); |
| 73 | + } |
| 74 | +} |
0 commit comments