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

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