PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Profiler/RedisProfilerStorage.php

https://bitbucket.org/hill2steve/mobileroom
PHP | 373 lines | 208 code | 71 blank | 94 comment | 30 complexity | c2bde7341721b4ebb335efdb6875a535 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\Profiler;
  11. use Redis;
  12. /**
  13. * RedisProfilerStorage stores profiling information in Redis.
  14. *
  15. * @author Andrej Hudec <pulzarraider@gmail.com>
  16. */
  17. class RedisProfilerStorage implements ProfilerStorageInterface
  18. {
  19. const TOKEN_PREFIX = 'sf_profiler_';
  20. const REDIS_OPT_SERIALIZER = 1;
  21. const REDIS_OPT_PREFIX = 2;
  22. const REDIS_SERIALIZER_NONE = 0;
  23. const REDIS_SERIALIZER_PHP = 1;
  24. protected $dsn;
  25. protected $lifetime;
  26. /**
  27. * @var Redis
  28. */
  29. private $redis;
  30. /**
  31. * Constructor.
  32. *
  33. * @param string $dsn A data source name
  34. * @param string $username Not used
  35. * @param string $password Not used
  36. * @param int $lifetime The lifetime to use for the purge
  37. */
  38. public function __construct($dsn, $username = '', $password = '', $lifetime = 86400)
  39. {
  40. $this->dsn = $dsn;
  41. $this->lifetime = (int) $lifetime;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function find($ip, $url, $limit, $method)
  47. {
  48. $indexName = $this->getIndexName();
  49. if (!$indexContent = $this->getValue($indexName, self::REDIS_SERIALIZER_NONE)) {
  50. return array();
  51. }
  52. $profileList = array_reverse(explode("\n", $indexContent));
  53. $result = array();
  54. foreach ($profileList as $item) {
  55. if ($limit === 0) {
  56. break;
  57. }
  58. if ($item == '') {
  59. continue;
  60. }
  61. list($itemToken, $itemIp, $itemMethod, $itemUrl, $itemTime, $itemParent) = explode("\t", $item, 6);
  62. if ($ip && false === strpos($itemIp, $ip) || $url && false === strpos($itemUrl, $url) || $method && false === strpos($itemMethod, $method)) {
  63. continue;
  64. }
  65. $result[] = array(
  66. 'token' => $itemToken,
  67. 'ip' => $itemIp,
  68. 'method' => $itemMethod,
  69. 'url' => $itemUrl,
  70. 'time' => $itemTime,
  71. 'parent' => $itemParent,
  72. );
  73. --$limit;
  74. }
  75. return $result;
  76. }
  77. /**
  78. * {@inheritdoc}
  79. */
  80. public function purge()
  81. {
  82. // delete only items from index
  83. $indexName = $this->getIndexName();
  84. $indexContent = $this->getValue($indexName, self::REDIS_SERIALIZER_NONE);
  85. if (!$indexContent) {
  86. return false;
  87. }
  88. $profileList = explode("\n", $indexContent);
  89. $result = array();
  90. foreach ($profileList as $item) {
  91. if ($item == '') {
  92. continue;
  93. }
  94. if (false !== $pos = strpos($item, "\t")) {
  95. $result[] = $this->getItemName(substr($item, 0, $pos));
  96. }
  97. }
  98. $result[] = $indexName;
  99. return $this->delete($result);
  100. }
  101. /**
  102. * {@inheritdoc}
  103. */
  104. public function read($token)
  105. {
  106. if (empty($token)) {
  107. return false;
  108. }
  109. $profile = $this->getValue($this->getItemName($token), self::REDIS_SERIALIZER_PHP);
  110. if (false !== $profile) {
  111. $profile = $this->createProfileFromData($token, $profile);
  112. }
  113. return $profile;
  114. }
  115. /**
  116. * {@inheritdoc}
  117. */
  118. public function write(Profile $profile)
  119. {
  120. $data = array(
  121. 'token' => $profile->getToken(),
  122. 'parent' => $profile->getParentToken(),
  123. 'children' => array_map(function ($p) { return $p->getToken(); }, $profile->getChildren()),
  124. 'data' => $profile->getCollectors(),
  125. 'ip' => $profile->getIp(),
  126. 'method' => $profile->getMethod(),
  127. 'url' => $profile->getUrl(),
  128. 'time' => $profile->getTime(),
  129. );
  130. $profileIndexed = false !== $this->getValue($this->getItemName($profile->getToken()));
  131. if ($this->setValue($this->getItemName($profile->getToken()), $data, $this->lifetime, self::REDIS_SERIALIZER_PHP)) {
  132. if (!$profileIndexed) {
  133. // Add to index
  134. $indexName = $this->getIndexName();
  135. $indexRow = implode("\t", array(
  136. $profile->getToken(),
  137. $profile->getIp(),
  138. $profile->getMethod(),
  139. $profile->getUrl(),
  140. $profile->getTime(),
  141. $profile->getParentToken(),
  142. ))."\n";
  143. return $this->appendValue($indexName, $indexRow, $this->lifetime);
  144. }
  145. return true;
  146. }
  147. return false;
  148. }
  149. /**
  150. * Internal convenience method that returns the instance of Redis.
  151. *
  152. * @return Redis
  153. */
  154. protected function getRedis()
  155. {
  156. if (null === $this->redis) {
  157. if (!preg_match('#^redis://(?(?=\[.*\])\[(.*)\]|(.*)):(.*)$#', $this->dsn, $matches)) {
  158. throw new \RuntimeException(sprintf('Please check your configuration. You are trying to use Redis with an invalid dsn "%s". The expected format is "redis://[host]:port".', $this->dsn));
  159. }
  160. $host = $matches[1] ?: $matches[2];
  161. $port = $matches[3];
  162. if (!extension_loaded('redis')) {
  163. throw new \RuntimeException('RedisProfilerStorage requires that the redis extension is loaded.');
  164. }
  165. $redis = new Redis;
  166. $redis->connect($host, $port);
  167. $redis->setOption(self::REDIS_OPT_PREFIX, self::TOKEN_PREFIX);
  168. $this->redis = $redis;
  169. }
  170. return $this->redis;
  171. }
  172. /**
  173. * Set instance of the Redis
  174. *
  175. * @param Redis $redis
  176. */
  177. public function setRedis($redis)
  178. {
  179. $this->redis = $redis;
  180. }
  181. private function createProfileFromData($token, $data, $parent = null)
  182. {
  183. $profile = new Profile($token);
  184. $profile->setIp($data['ip']);
  185. $profile->setMethod($data['method']);
  186. $profile->setUrl($data['url']);
  187. $profile->setTime($data['time']);
  188. $profile->setCollectors($data['data']);
  189. if (!$parent && $data['parent']) {
  190. $parent = $this->read($data['parent']);
  191. }
  192. if ($parent) {
  193. $profile->setParent($parent);
  194. }
  195. foreach ($data['children'] as $token) {
  196. if (!$token) {
  197. continue;
  198. }
  199. if (!$childProfileData = $this->getValue($this->getItemName($token), self::REDIS_SERIALIZER_PHP)) {
  200. continue;
  201. }
  202. $profile->addChild($this->createProfileFromData($token, $childProfileData, $profile));
  203. }
  204. return $profile;
  205. }
  206. /**
  207. * Gets the item name.
  208. *
  209. * @param string $token
  210. *
  211. * @return string
  212. */
  213. private function getItemName($token)
  214. {
  215. $name = $token;
  216. if ($this->isItemNameValid($name)) {
  217. return $name;
  218. }
  219. return false;
  220. }
  221. /**
  222. * Gets the name of the index.
  223. *
  224. * @return string
  225. */
  226. private function getIndexName()
  227. {
  228. $name = 'index';
  229. if ($this->isItemNameValid($name)) {
  230. return $name;
  231. }
  232. return false;
  233. }
  234. private function isItemNameValid($name)
  235. {
  236. $length = strlen($name);
  237. if ($length > 2147483648) {
  238. throw new \RuntimeException(sprintf('The Redis item key "%s" is too long (%s bytes). Allowed maximum size is 2^31 bytes.', $name, $length));
  239. }
  240. return true;
  241. }
  242. /**
  243. * Retrieves an item from the Redis server.
  244. *
  245. * @param string $key
  246. * @param int $serializer
  247. *
  248. * @return mixed
  249. */
  250. private function getValue($key, $serializer = self::REDIS_SERIALIZER_NONE)
  251. {
  252. $redis = $this->getRedis();
  253. $redis->setOption(self::REDIS_OPT_SERIALIZER, $serializer);
  254. return $redis->get($key);
  255. }
  256. /**
  257. * Stores an item on the Redis server under the specified key.
  258. *
  259. * @param string $key
  260. * @param mixed $value
  261. * @param int $expiration
  262. * @param int $serializer
  263. *
  264. * @return Boolean
  265. */
  266. private function setValue($key, $value, $expiration = 0, $serializer = self::REDIS_SERIALIZER_NONE)
  267. {
  268. $redis = $this->getRedis();
  269. $redis->setOption(self::REDIS_OPT_SERIALIZER, $serializer);
  270. return $redis->setex($key, $expiration, $value);
  271. }
  272. /**
  273. * Appends data to an existing item on the Redis server.
  274. *
  275. * @param string $key
  276. * @param string $value
  277. * @param int $expiration
  278. *
  279. * @return Boolean
  280. */
  281. private function appendValue($key, $value, $expiration = 0)
  282. {
  283. $redis = $this->getRedis();
  284. $redis->setOption(self::REDIS_OPT_SERIALIZER, self::REDIS_SERIALIZER_NONE);
  285. if ($redis->exists($key)) {
  286. $redis->append($key, $value);
  287. return $redis->setTimeout($key, $expiration);
  288. }
  289. return $redis->setex($key, $expiration, $value);
  290. }
  291. /**
  292. * Removes the specified keys.
  293. *
  294. * @param array $keys
  295. *
  296. * @return Boolean
  297. */
  298. private function delete(array $keys)
  299. {
  300. return (bool) $this->getRedis()->delete($keys);
  301. }
  302. }