Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
17 / 17 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| JsonWordCounter | |
100.00% |
17 / 17 |
|
100.00% |
3 / 3 |
12 | |
100.00% |
1 / 1 |
| __construct | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
| isSupported | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| count | |
100.00% |
14 / 14 |
|
100.00% |
1 / 1 |
8 | |||
| countFromString | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | namespace Apie\CountWords\Strategies; |
| 3 | |
| 4 | use Apie\CountWords\Strategies\Concerns\UseResourceForFile; |
| 5 | use Apie\CountWords\Strategies\Concerns\UseStringForResource; |
| 6 | use Apie\CountWords\WordCounter; |
| 7 | |
| 8 | final class JsonWordCounter implements WordCounterInterface |
| 9 | { |
| 10 | use UseStringForResource; |
| 11 | use UseResourceForFile; |
| 12 | /** |
| 13 | * @codeCoverageIgnore |
| 14 | */ |
| 15 | private function __construct() |
| 16 | { |
| 17 | } |
| 18 | |
| 19 | public static function isSupported(?string $fileExtension, ?string $mimeType): bool |
| 20 | { |
| 21 | return in_array($fileExtension, ['json', 'jsonld']) || in_array($mimeType, ['application/json', 'application/ld+json']); |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * @param array<string, int> $counts |
| 26 | * @return array<string, int> |
| 27 | */ |
| 28 | private static function count(mixed $decoded, array $counts = []): array |
| 29 | { |
| 30 | if ($decoded === null) { |
| 31 | return $counts; |
| 32 | } |
| 33 | switch (get_debug_type($decoded)) { |
| 34 | case 'string': |
| 35 | return WordCounter::countFromString($decoded, $counts); |
| 36 | case 'int': |
| 37 | case 'float': |
| 38 | return WordCounter::countFromString((string) $decoded, $counts); |
| 39 | default: |
| 40 | $checkKeys = substr(json_encode($decoded), 0, 1) === '{'; |
| 41 | foreach ($decoded as $key => $value) { |
| 42 | if ($checkKeys) { |
| 43 | $counts = WordCounter::countFromString((string) $key, $counts); |
| 44 | } |
| 45 | $counts = self::count($value, $counts); |
| 46 | } |
| 47 | } |
| 48 | return $counts; |
| 49 | } |
| 50 | |
| 51 | public static function countFromString(string $text, array $counts = []): array |
| 52 | { |
| 53 | $decoded = json_decode($text, true); |
| 54 | return self::count($decoded, $counts); |
| 55 | } |
| 56 | } |