Passed
Push — task/2976_TYPO3.11_compatibili... ( 9f9205...0f123d )
by Rafael
27:04
created

SynonymParser::parseJson()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.1755

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 15
ccs 7
cts 9
cp 0.7778
rs 9.9666
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4.1755
1
<?php
2
3
namespace ApacheSolrForTypo3\Solr\System\Solr\Parser;
4
5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
 * It is free software; you can redistribute it and/or modify it under
9
 * the terms of the GNU General Public License, either version 2
10
 * of the License, or any later version.
11
 *
12
 * For the full copyright and license information, please read the
13
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
 * The TYPO3 project - inspiring people to share!
16
 */
17
18
/**
19
 * Class to parse the synonyms from a solr response.
20
 *
21
 * @author Timo Hund <[email protected]>
22
 */
23
class SynonymParser
24
{
25
    /**
26
     * Parse the solr synonyms response from a json string to an array.
27
     *
28
     * @param string $baseWord
29
     * @param string $jsonString
30
     * @return array
31
     */
32 8
    public function parseJson(string $baseWord, string $jsonString): array
33
    {
34 8
        $decodedResponse = json_decode($jsonString);
35 8
        $synonyms = [];
36 8
        if (!empty($baseWord)) {
37 8
            if (is_array($decodedResponse->{$baseWord})) {
38 8
                $synonyms = $decodedResponse->{$baseWord};
39
            }
40
        } else {
41
            if (isset($decodedResponse->synonymMappings->managedMap)) {
42
                $synonyms = (array)$decodedResponse->synonymMappings->managedMap;
43
            }
44
        }
45
46 8
        return $synonyms;
47
    }
48
49
    /**
50
     * @param string $baseWord
51
     * @param array $synonyms
52
     * @return string
53
     */
54 7
    public function toJson(string $baseWord, array $synonyms): string
55
    {
56 7
        return json_encode([$baseWord => $synonyms]);
57
    }
58
}
59