Mapper::toList()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 10
cts 10
cp 1
rs 9.7666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Pinterest PHP library.
5
 *
6
 * (c) Hans Ott <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.md.
10
 *
11
 * Source: https://github.com/hansott/pinterest-php
12
 */
13
14
namespace Pinterest;
15
16
use JsonMapper;
17
use ArrayObject;
18
use Pinterest\Http\Response;
19
use Pinterest\Objects\PagedList;
20
use Pinterest\Objects\BaseObject;
21
22
/**
23
 * This class maps an object to a response.
24
 *
25
 * @author Hans Ott <[email protected]>
26
 */
27
final class Mapper
28
{
29
    protected $mapper;
30
31
    protected $class;
32
33 11
    public function __construct(BaseObject $class)
34
    {
35 11
        $this->class = $class;
36 11
        $this->mapper = new JsonMapper();
37 11
        $this->mapper->bStrictNullTypes = false;    // don't throw exception if any field is null
38 11
    }
39
40 5
    public function toSingle(Response $response)
41
    {
42 5
        $data = $response->body->data;
43
44 5
        return $this->mapper->map($data, $this->class);
45
    }
46
47
    /**
48
     * Converts an array object to array.
49
     *
50
     * @param \ArrayObject $object The array object to convert.
51
     *
52
     * @return array The converted array.
53
     */
54 6
    private function convertToArray(ArrayObject $object)
55
    {
56 6
        $arr = array();
57 6
        $iterator = $object->getIterator();
58 6
        while ($iterator->valid()) {
59 4
            $arr[] = $iterator->current();
60 4
            $iterator->next();
61 2
        }
62
63 6
        return $arr;
64
    }
65
66 6
    public function toList(Response $response)
67
    {
68 6
        $data = $response->body->data;
69 6
        $nextUrl = isset($response->body->page->next) ? $response->body->page->next : null;
70
71 6
        $items = $this->mapper->mapArray(
72 6
            $data,
73 6
            new ArrayObject(),
74 6
            get_class($this->class)
75 3
        );
76
77 6
        $items = $this->convertToArray($items);
78
79 6
        return new PagedList($items, $nextUrl);
80
    }
81
}
82