Passed
Pull Request — master (#276)
by
unknown
03:24
created

Findable::findRelated()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php namespace Picqer\Financials\Exact\Query;
2
3
use Picqer\Financials\Exact\Connection;
4
use Picqer\Financials\Exact\Model;
5
6
trait Findable
7
{
8
    /**
9
     * @return Connection
10
     */
11
    abstract function connection();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
12
13
    abstract function isFillable($key);
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
14
15
    /**
16
     * @return string
17
     */
18
    abstract function url();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
19
20
    /**
21
     * @return string
22
     */
23
    abstract function primaryKey();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
24
25
    public function find($id)
26
    {
27
        $filter = $this->primaryKey() . " eq guid'$id'";
28
29
        if ($this->primaryKey() === 'Code') {
30
            $filter = $this->primaryKey() . " eq $id";
31
        }
32
33
        $records = $this->connection()->get($this->url(), [
34
            '$filter' => $filter,
35
            '$top' => 1, // The result will always be 1 but on some entities Exact gives an error without it.
36
        ]);
37
38
        $result = isset($records[0]) ? $records[0] : [];
39
        return new self($this->connection(), $result);
0 ignored issues
show
Unused Code introduced by
The call to Picqer\Financials\Exact\...Findable::__construct() has too many arguments starting with $this->connection(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

39
        return /** @scrutinizer ignore-call */ new self($this->connection(), $result);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
40
    }
41
42
    public function findWithSelect($id, $select = '')
43
    {
44
        //eg: $oAccounts->findWithSelect('5b7f4515-b7a0-4839-ac69-574968677d96', 'Code, Name');
45
        $result = $this->connection()->get($this->url(), [
46
            '$filter' => $this->primaryKey() . " eq guid'$id'",
47
            '$select' => $select
48
        ]);
49
50
        return new self($this->connection(), $result);
0 ignored issues
show
Unused Code introduced by
The call to Picqer\Financials\Exact\...Findable::__construct() has too many arguments starting with $this->connection(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

50
        return /** @scrutinizer ignore-call */ new self($this->connection(), $result);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
51
    }
52
53
54
    /**
55
     * Return the value of the primary key
56
     *
57
     * @param string $code the value to search for
58
     * @param string $key  the key being searched (defaults to 'Code')
59
     *
60
     * @return string (guid)
61
     */
62
    public function findId($code, $key='Code')
63
    {
64
        if ($this->isFillable($key)) {
65
            $format = ($this->url() == 'crm/Accounts' && $key === 'Code') ? '%18s' : '%s';
66
            if (preg_match('/^[\w]{8}-([\w]{4}-){3}[\w]{12}$/', $code)) {
67
                $format = "guid'$format'";
68
            }
69
            elseif (is_string($code)) {
0 ignored issues
show
introduced by
The condition is_string($code) is always true.
Loading history...
70
                $format = "'$format'";
71
            }
72
73
            $filter = sprintf("$key eq $format", $code);
74
            $request = [
75
                '$filter' => $filter,
76
                '$top' => 1,
77
                '$select' => $this->primaryKey(),
78
                '$orderby' => $this->primaryKey(),
79
            ];
80
            if ($records = $this->connection()->get($this->url(), $request)) {
81
                return $records[0][$this->primaryKey()];
82
            }
83
        }
84
    }
85
86
    /**
87
     * @param $model
88
     * @return self|null
89
     */
90
    public function firstRelated($model)
91
    {
92
        $related = $this->findRelated($model);
93
94
        if ($related) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $related of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
95
            return $related[0];
96
        }
97
98
        return null;
99
    }
100
101
    /**
102
     * @param Model $model
103
     * @return array
104
     */
105
    public function findRelated($model)
106
    {
107
        $baseName = $this->getModelBaseName($model);
108
109
        $filter = $baseName.' eq guid\''.$model->primaryKeyContent() .'\'';
110
111
        $filtered = $this->filter($filter);
112
113
        return $filtered;
114
    }
115
116
    private function getModelBaseName($class)
117
    {
118
        $class = is_object($class) ? get_class($class) : $class;
119
120
        return basename(str_replace('\\', '/', $class));
121
    }
122
123
    public function filter($filter, $expand = '', $select = '', $system_query_options = null, array $headers = [])
124
    {
125
        $originalDivision = $this->connection()->getDivision();
126
127
        if ($this->isFillable('Division') && preg_match("@Division[\t\r\n ]+eq[\t\r\n ]+([0-9]+)@i", $filter, $divisionId)) {
128
            $this->connection()->setDivision($divisionId[1]); // Fix division
129
        }
130
131
        $request = [
132
            '$filter' => $filter
133
        ];
134
        if (strlen($expand) > 0) {
135
            $request['$expand'] = $expand;
136
        }
137
        if (strlen($select) > 0) {
138
            $request['$select'] = $select;
139
        }
140
        if (is_array($system_query_options)) {
141
            // merge in other options
142
            // no verification of proper system query options
143
            $request = array_merge($system_query_options, $request);
144
        }
145
146
        $result = $this->connection()->get($this->url(), $request, $headers);
147
148
        if (!empty($divisionId)) {
149
            $this->connection()->setDivision($originalDivision); // Restore division
150
        }
151
152
        return $this->collectionFromResult($result);
153
    }
154
155
156
    /**
157
     * Returns the first Financial model in by applying $top=1 to the query string.
158
     *
159
     * @return \Picqer\Financials\Exact\Model|null
160
     */
161
    public function first()
162
    {
163
        $results = $this->filter('', '', '', ['$top'=> 1]);
164
        $result = is_array($results) && count($results) > 0 ? $results[0] : null;
165
166
        return $result;
167
    }
168
169
    public function getResultSet(array $params = [])
170
    {
171
        return new Resultset($this->connection(), $this->url(), get_class($this), $params);
172
    }
173
174
    public function get(array $params = [])
175
    {
176
        $result = $this->connection()->get($this->url(), $params);
177
178
        return $this->collectionFromResult($result);
179
    }
180
181
182
    public function collectionFromResult($result)
183
    {
184
        // If we have one result which is not an assoc array, make it the first element of an array for the
185
        // collectionFromResult function so we always return a collection from filter
186
        if ((bool) count(array_filter(array_keys($result), 'is_string'))) {
187
            $result = [$result];
188
        }
189
190
        while ($this->connection()->nextUrl !== null)
191
        {
192
            $nextResult = $this->connection()->get($this->connection()->nextUrl);
193
            
194
            // If we have one result which is not an assoc array, make it the first element of an array for the array_merge function
195
            if ((bool) count(array_filter(array_keys($nextResult), 'is_string'))) {
196
                $nextResult = [$nextResult];
197
            }
198
            
199
            $result = array_merge($result, $nextResult);
200
        }
201
        $collection = [];
202
        foreach ($result as $r) {
203
            $collection[] = new self($this->connection(), $r);
0 ignored issues
show
Unused Code introduced by
The call to Picqer\Financials\Exact\...Findable::__construct() has too many arguments starting with $this->connection(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

203
            $collection[] = /** @scrutinizer ignore-call */ new self($this->connection(), $r);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
204
        }
205
206
        return $collection;
207
    }
208
}
209