MemcachedCaster.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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\VarDumper\Caster;
  11. use Symfony\Component\VarDumper\Cloner\Stub;
  12. /**
  13. * @author Jan Schädlich <jan.schaedlich@sensiolabs.de>
  14. */
  15. class MemcachedCaster
  16. {
  17. private static $optionConstants;
  18. private static $defaultOptions;
  19. public static function castMemcached(\Memcached $c, array $a, Stub $stub, $isNested)
  20. {
  21. $a += [
  22. Caster::PREFIX_VIRTUAL.'servers' => $c->getServerList(),
  23. Caster::PREFIX_VIRTUAL.'options' => new EnumStub(
  24. self::getNonDefaultOptions($c)
  25. ),
  26. ];
  27. return $a;
  28. }
  29. private static function getNonDefaultOptions(\Memcached $c)
  30. {
  31. self::$defaultOptions = self::$defaultOptions ?? self::discoverDefaultOptions();
  32. self::$optionConstants = self::$optionConstants ?? self::getOptionConstants();
  33. $nonDefaultOptions = [];
  34. foreach (self::$optionConstants as $constantKey => $value) {
  35. if (self::$defaultOptions[$constantKey] !== $option = $c->getOption($value)) {
  36. $nonDefaultOptions[$constantKey] = $option;
  37. }
  38. }
  39. return $nonDefaultOptions;
  40. }
  41. private static function discoverDefaultOptions()
  42. {
  43. $defaultMemcached = new \Memcached();
  44. $defaultMemcached->addServer('127.0.0.1', 11211);
  45. $defaultOptions = [];
  46. self::$optionConstants = self::$optionConstants ?? self::getOptionConstants();
  47. foreach (self::$optionConstants as $constantKey => $value) {
  48. $defaultOptions[$constantKey] = $defaultMemcached->getOption($value);
  49. }
  50. return $defaultOptions;
  51. }
  52. private static function getOptionConstants()
  53. {
  54. $reflectedMemcached = new \ReflectionClass(\Memcached::class);
  55. $optionConstants = [];
  56. foreach ($reflectedMemcached->getConstants() as $constantKey => $value) {
  57. if (0 === strpos($constantKey, 'OPT_')) {
  58. $optionConstants[$constantKey] = $value;
  59. }
  60. }
  61. return $optionConstants;
  62. }
  63. }