blob: cfef19acc3f43a37f79d811d5cb2ccfcb7538b49 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\VarDumper\Caster;
13
14use Symfony\Component\VarDumper\Cloner\Stub;
15
16/**
17 * @author Jan Schädlich <jan.schaedlich@sensiolabs.de>
18 *
19 * @final
20 */
21class MemcachedCaster
22{
23 private static $optionConstants;
24 private static $defaultOptions;
25
26 public static function castMemcached(\Memcached $c, array $a, Stub $stub, bool $isNested)
27 {
28 $a += [
29 Caster::PREFIX_VIRTUAL.'servers' => $c->getServerList(),
30 Caster::PREFIX_VIRTUAL.'options' => new EnumStub(
31 self::getNonDefaultOptions($c)
32 ),
33 ];
34
35 return $a;
36 }
37
38 private static function getNonDefaultOptions(\Memcached $c): array
39 {
40 self::$defaultOptions = self::$defaultOptions ?? self::discoverDefaultOptions();
41 self::$optionConstants = self::$optionConstants ?? self::getOptionConstants();
42
43 $nonDefaultOptions = [];
44 foreach (self::$optionConstants as $constantKey => $value) {
45 if (self::$defaultOptions[$constantKey] !== $option = $c->getOption($value)) {
46 $nonDefaultOptions[$constantKey] = $option;
47 }
48 }
49
50 return $nonDefaultOptions;
51 }
52
53 private static function discoverDefaultOptions(): array
54 {
55 $defaultMemcached = new \Memcached();
56 $defaultMemcached->addServer('127.0.0.1', 11211);
57
58 $defaultOptions = [];
59 self::$optionConstants = self::$optionConstants ?? self::getOptionConstants();
60
61 foreach (self::$optionConstants as $constantKey => $value) {
62 $defaultOptions[$constantKey] = $defaultMemcached->getOption($value);
63 }
64
65 return $defaultOptions;
66 }
67
68 private static function getOptionConstants(): array
69 {
70 $reflectedMemcached = new \ReflectionClass(\Memcached::class);
71
72 $optionConstants = [];
73 foreach ($reflectedMemcached->getConstants() as $constantKey => $value) {
74 if (str_starts_with($constantKey, 'OPT_')) {
75 $optionConstants[$constantKey] = $value;
76 }
77 }
78
79 return $optionConstants;
80 }
81}