Completed
Branch feature/split-orm (fa2f8e)
by Anton
03:35
created

DocumentCursor   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 76
rs 10
c 0
b 0
f 0
wmc 6
lcom 1
cbo 1

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 1
A current() 0 4 1
A getCursor() 0 4 1
A toArray() 0 4 1
A fetchAll() 0 9 2
1
<?php
2
/**
3
 * components
4
 *
5
 * @author    Wolfy-J
6
 */
7
namespace Spiral\ODM\Entities;
8
9
use MongoDB\Driver\Cursor;
10
use Spiral\ODM\CompositableInterface;
11
use Spiral\ODM\ODMInterface;
12
13
/**
14
 * Iterates over given cursor and convert its values in a proper objects using instantiation
15
 * manager. Attention, this class is very important as it provides ability to story inherited
16
 * documents in one collection.
17
 *
18
 * Note: since new mongo drivers arrived you can emulate same functionality using '__pclass'
19
 * property.
20
 */
21
class DocumentCursor extends \IteratorIterator
22
{
23
    /**
24
     * @var Cursor
25
     */
26
    private $cursor;
27
28
    /**
29
     * @var string
30
     */
31
    private $class;
32
33
    /**
34
     * @var ODMInterface
35
     */
36
    private $odm;
37
38
    /**
39
     * @param Cursor       $cursor
40
     * @param string       $class
41
     * @param ODMInterface $odm
42
     */
43
    public function __construct(Cursor $cursor, string $class, ODMInterface $odm)
44
    {
45
        //Ensuring cursor fetch types
46
        $cursor->setTypeMap([
47
            'root'     => 'array',
48
            'document' => 'array',
49
            'array'    => 'array'
50
        ]);
51
52
        parent::__construct($cursor);
53
54
        $this->class = $class;
55
        $this->odm = $odm;
56
    }
57
58
    /**
59
     * @return \Spiral\ODM\CompositableInterface
60
     */
61
    public function current(): CompositableInterface
62
    {
63
        return $this->odm->instantiate($this->class, parent::current());
64
    }
65
66
    /**
67
     * @return Cursor
68
     */
69
    public function getCursor(): Cursor
70
    {
71
        return $this->cursor;
72
    }
73
74
    /**
75
     * @return array
76
     */
77
    public function toArray(): array
78
    {
79
        return $this->fetchAll();
80
    }
81
82
    /**
83
     * Fetch all documents.
84
     *
85
     * @return CompositableInterface[]
86
     */
87
    public function fetchAll(): array
88
    {
89
        $result = [];
90
        foreach ($this as $item) {
91
            $result[] = $item;
92
        }
93
94
        return $result;
95
    }
96
}