| Conditions | 12 |
| Paths | 33 |
| Total Lines | 55 |
| Code Lines | 32 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 29 | public function syncFromJson(?string $json, bool $allowDeletes = false): array |
||
| 30 | { |
||
| 31 | $json = trim((string) $json); |
||
| 32 | |||
| 33 | if ('' === $json) { |
||
| 34 | return ['created' => 0, 'updated' => 0, 'deleted' => 0]; |
||
| 35 | } |
||
| 36 | |||
| 37 | $desired = $this->parseJsonToCodeTitleMap($json); // code => title |
||
| 38 | |||
| 39 | /** @var SearchEngineField[] $existing */ |
||
| 40 | $existing = $this->entityManager->getRepository(SearchEngineField::class)->findAll(); |
||
| 41 | |||
| 42 | $existingByCode = []; |
||
| 43 | foreach ($existing as $field) { |
||
| 44 | $existingByCode[$field->getCode()] = $field; |
||
| 45 | } |
||
| 46 | |||
| 47 | $created = 0; |
||
| 48 | $updated = 0; |
||
| 49 | $deleted = 0; |
||
| 50 | |||
| 51 | foreach ($desired as $code => $title) { |
||
| 52 | if (isset($existingByCode[$code])) { |
||
| 53 | $field = $existingByCode[$code]; |
||
| 54 | |||
| 55 | if ($field->getTitle() !== $title) { |
||
| 56 | $field->setTitle($title); |
||
| 57 | $this->entityManager->persist($field); |
||
| 58 | $updated++; |
||
| 59 | } |
||
| 60 | } else { |
||
| 61 | $field = (new SearchEngineField()) |
||
| 62 | ->setCode($code) |
||
| 63 | ->setTitle($title); |
||
| 64 | |||
| 65 | $this->entityManager->persist($field); |
||
| 66 | $created++; |
||
| 67 | } |
||
| 68 | } |
||
| 69 | |||
| 70 | if ($allowDeletes) { |
||
| 71 | foreach ($existingByCode as $code => $field) { |
||
| 72 | if (!isset($desired[$code])) { |
||
| 73 | $this->entityManager->remove($field); |
||
| 74 | $deleted++; |
||
| 75 | } |
||
| 76 | } |
||
| 77 | } |
||
| 78 | |||
| 79 | if ($created > 0 || $updated > 0 || $deleted > 0) { |
||
| 80 | $this->entityManager->flush(); |
||
| 81 | } |
||
| 82 | |||
| 83 | return ['created' => $created, 'updated' => $updated, 'deleted' => $deleted]; |
||
| 84 | } |
||
| 216 |