Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 1 | <?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 | |
| 12 | namespace Symfony\Component\VarDumper\Caster; |
| 13 | |
| 14 | use Symfony\Component\VarDumper\Cloner\Stub; |
| 15 | |
| 16 | /** |
| 17 | * @author Jan Schädlich <jan.schaedlich@sensiolabs.de> |
| 18 | * |
| 19 | * @final |
| 20 | */ |
| 21 | class MemcachedCaster |
| 22 | { |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 23 | private static array $optionConstants; |
| 24 | private static array $defaultOptions; |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 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 | } |