Completed
Pull Request — master (#276)
by
unknown
04:07 queued 01:48
created

Findable::getModelBaseName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 2
nc 2
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 $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
        return $this->filter($filter);
112
    }
113
114
    /**
115
     * @param string|object $class
116
     * @return string
117
     */
118
    private function getModelBaseName($class)
119
    {
120
        $class = is_object($class) ? get_class($class) : $class;
121
122
        return basename(str_replace('\\', '/', $class));
123
    }
124
125
    public function filter($filter, $expand = '', $select = '', $system_query_options = null, array $headers = [])
126
    {
127
        $originalDivision = $this->connection()->getDivision();
128
129
        if ($this->isFillable('Division') && preg_match("@Division[\t\r\n ]+eq[\t\r\n ]+([0-9]+)@i", $filter, $divisionId)) {
130
            $this->connection()->setDivision($divisionId[1]); // Fix division
131
        }
132
133
        $request = [
134
            '$filter' => $filter
135
        ];
136
        if (strlen($expand) > 0) {
137
            $request['$expand'] = $expand;
138
        }
139
        if (strlen($select) > 0) {
140
            $request['$select'] = $select;
141
        }
142
        if (is_array($system_query_options)) {
143
            // merge in other options
144
            // no verification of proper system query options
145
            $request = array_merge($system_query_options, $request);
146
        }
147
148
        $result = $this->connection()->get($this->url(), $request, $headers);
149
150
        if (!empty($divisionId)) {
151
            $this->connection()->setDivision($originalDivision); // Restore division
152
        }
153
154
        return $this->collectionFromResult($result);
155
    }
156
157
158
    /**
159
     * Returns the first Financial model in by applying $top=1 to the query string.
160
     *
161
     * @return \Picqer\Financials\Exact\Model|null
162
     */
163
    public function first()
164
    {
165
        $results = $this->filter('', '', '', ['$top'=> 1]);
166
        $result = is_array($results) && count($results) > 0 ? $results[0] : null;
167
168
        return $result;
169
    }
170
171
    public function getResultSet(array $params = [])
172
    {
173
        return new Resultset($this->connection(), $this->url(), get_class($this), $params);
174
    }
175
176
    public function get(array $params = [])
177
    {
178
        $result = $this->connection()->get($this->url(), $params);
179
180
        return $this->collectionFromResult($result);
181
    }
182
183
184
    public function collectionFromResult($result)
185
    {
186
        // If we have one result which is not an assoc array, make it the first element of an array for the
187
        // collectionFromResult function so we always return a collection from filter
188
        if ((bool) count(array_filter(array_keys($result), 'is_string'))) {
189
            $result = [$result];
190
        }
191
192
        while ($this->connection()->nextUrl !== null)
193
        {
194
            $nextResult = $this->connection()->get($this->connection()->nextUrl);
195
            
196
            // If we have one result which is not an assoc array, make it the first element of an array for the array_merge function
197
            if ((bool) count(array_filter(array_keys($nextResult), 'is_string'))) {
198
                $nextResult = [$nextResult];
199
            }
200
            
201
            $result = array_merge($result, $nextResult);
202
        }
203
        $collection = [];
204
        foreach ($result as $r) {
205
            $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

205
            $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...
206
        }
207
208
        return $collection;
209
    }
210
}
211