From 6801b8a5fa84a84cb07dbe21e81c5dcba5884add Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Burnichon?= Date: Thu, 14 Apr 2016 15:09:20 +0200 Subject: [PATCH] reduce fetchAndSave complexity --- .../CachedMediaSubdefDataRepository.php | 49 ++++++++++++++----- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/lib/Alchemy/Phrasea/Databox/Subdef/CachedMediaSubdefDataRepository.php b/lib/Alchemy/Phrasea/Databox/Subdef/CachedMediaSubdefDataRepository.php index e576a6b1f1..712575c628 100644 --- a/lib/Alchemy/Phrasea/Databox/Subdef/CachedMediaSubdefDataRepository.php +++ b/lib/Alchemy/Phrasea/Databox/Subdef/CachedMediaSubdefDataRepository.php @@ -181,21 +181,11 @@ class CachedMediaSubdefDataRepository implements MediaSubdefDataRepository { $retrieved = $this->decorated->findByRecordIdsAndNames($recordIds, $names); - if (null === $names) { - $extra = array_fill_keys($this->generateAllCacheKeys($recordIds), []); + $data = $this->normalizeRetrievedData($retrieved, $keys); - foreach ($retrieved as $item) { - $extra[$this->getCacheKey($item['record_id'])][] = $this->getCacheKey($item['record_id'], $item['name']); - } - } + $toCache = null === $names ? $this->appendCacheExtraData($data, $retrieved, $recordIds) : $data; - $data = array_fill_keys($keys, null); - - foreach ($retrieved as $item) { - $data[$this->dataToKey($item)] = $item; - } - - $this->cache->saveMultiple(isset($extra) ? array_merge($data, $extra) : $data, $this->lifeTime); + $this->cache->saveMultiple($toCache, $this->lifeTime); return $this->filterNonNull($data); } @@ -218,4 +208,37 @@ class CachedMediaSubdefDataRepository implements MediaSubdefDataRepository return count($keys) === count($data) ? call_user_func_array('array_merge', $data) : []; } + + /** + * @param array $retrieved + * @param array $keys + * @return array + */ + private function normalizeRetrievedData(array $retrieved, array $keys) + { + $data = array_fill_keys($keys, null); + + foreach ($retrieved as $item) { + $data[$this->dataToKey($item)] = $item; + } + + return $data; + } + + /** + * @param array $data + * @param array $retrieved + * @param array $recordIds + * @return array + */ + private function appendCacheExtraData(array $data, array $retrieved, array $recordIds) + { + $extra = array_fill_keys($this->generateAllCacheKeys($recordIds), []); + + foreach ($retrieved as $item) { + $extra[$this->getCacheKey($item['record_id'])][] = $this->getCacheKey($item['record_id'], $item['name']); + } + + return array_merge($data, $extra); + } }