Completed
Branch develop (45165d)
by Alexey
04:09
created

CategoriesScraper::__invoke()   B

Complexity

Conditions 9
Paths 6

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 39
rs 8.0555
c 0
b 0
f 0
cc 9
nc 6
nop 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Nelexa\GPlay\Scraper;
5
6
use Nelexa\GPlay\Exception\GooglePlayException;
7
use Nelexa\GPlay\Http\ResponseHandlerInterface;
8
use Nelexa\GPlay\Model\Category;
9
use Nelexa\GPlay\Util\ScraperUtil;
10
use Psr\Http\Message\RequestInterface;
11
use Psr\Http\Message\ResponseInterface;
12
13
class CategoriesScraper implements ResponseHandlerInterface
14
{
15
    private const CATEGORY_URL_PREFIX = '/store/apps/category/';
16
17
    /**
18
     * @param RequestInterface $request
19
     * @param ResponseInterface $response
20
     * @return mixed
21
     * @throws GooglePlayException
22
     */
23
    public function __invoke(RequestInterface $request, ResponseInterface $response)
24
    {
25
        $scriptData = ScraperUtil::extractScriptData($response->getBody()->getContents());
26
27
        $dataCategories = null;
28
        foreach ($scriptData as $key => $data) {
29
            if (isset($data[0][1][0][3][0]) && is_array($data[0][1][0][3][0])) {
30
                $dataCategories = $data;
31
                break;
32
            }
33
        }
34
35
        if ($dataCategories === null) {
36
            throw (new GooglePlayException('Failed to get the list of categories.'))
37
                ->setUrl($request->getUri()->__toString());
38
        }
39
40
        $parseCategories = static function (array $items) use (&$parseCategories) : array {
41
            return array_reduce($items, static function ($results, $item) use (&$parseCategories) {
42
                if (is_array($item)) {
43
                    if (
44
                        count($item) === 6 &&
45
                        strpos($item[0], self::CATEGORY_URL_PREFIX) === 0 &&
46
                        strpos($item[0], '?age=') === false
47
                    ) {
48
                        $id = basename($item[0]);
49
                        $categoryName = $item[1];
50
                        $results[] = new Category(
51
                            $id,
52
                            $categoryName
53
                        );
54
                    } else {
55
                        $results = array_merge($results, $parseCategories($item));
56
                    }
57
                }
58
                return $results;
59
            }, []);
60
        };
61
        return $parseCategories($dataCategories[0][1][0][3]);
62
    }
63
}
64