<?php

/**
 * Goes through all configured memcached slabs on the provided pre-configured Memcache object
 *
 * IMPORTANT: This is for the older and more limited https://pecl.php.net/package/memcache (no "d" suffix) and
 * NOT for https://pecl.php.net/package/memcached (has the "d" suffix)!
 * 
 * Inspired by (and modified from): https://coderwall.com/p/imot3w/php-memcache-list-keys
 *
 * @param	Memcache $memcache
 * @param	int	$limit
 * @return	array
 */
function getMemcacheKeys(Memcache $memcache, $limit = 10000) {
	$keysFound = array();

	$slabs = $memcache->getExtendedStats('slabs');

	foreach($slabs as $serverSlabs) {
		foreach($serverSlabs as $slabId => $slabMeta) {
			// Move on if not an actual integer (e.g. skip active_slabs).
			if (!is_numeric($slabId)) continue;

			try {
				$cacheDump = $memcache->getExtendedStats('cachedump', (int) $slabId, 1000);
			} catch(Exception $e) {
				continue;
			}

			if (!is_array($cacheDump)) {
				continue;
			}

			foreach($cacheDump as $dump) {

				if (!is_array($dump)) {
					continue;
				}

				foreach($dump as $key => $value) {
					$keysFound[] = $key;

					if (count($keysFound) >= $limit) {
						return $keysFound;
					}
				}
			}
		}
	}

	return $keysFound;
}