Completed
Branch EDTR/master (0d7008)
by
unknown
34:37 queued 26:06
created

AbstractLoader   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 69
rs 10
c 0
b 0
f 0
wmc 4
lcom 0
cbo 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
getQuery() 0 1 ?
getWhereParams() 0 1 ?
A loadKeys() 0 29 4
1
<?php
2
3
namespace EventEspresso\core\domain\services\graphql\data\loaders;
4
5
use WPGraphQL\Data\Loader\AbstractDataLoader;
6
7
/**
8
 * Class AbstractLoader
9
 */
10
abstract class AbstractLoader extends AbstractDataLoader
11
{
12
    protected $primaryKey;
13
14
    /**
15
     * @return EE_Base_Class
16
     * @throws EE_Error
17
     * @throws InvalidArgumentException
18
     * @throws InvalidDataTypeException
19
     * @throws InvalidInterfaceException
20
     */
21
    abstract protected function getQuery();
22
23
    /**
24
     * @param array $keys
25
     *
26
     * @return array
27
     * @throws EE_Error
28
     * @throws InvalidArgumentException
29
     * @throws InvalidDataTypeException
30
     * @throws InvalidInterfaceException
31
     */
32
    abstract protected function getWhereParams(array $keys);
33
34
    /**
35
     * Given array of keys, loads and returns a map consisting of keys from `keys` array and loaded
36
     * values
37
     *
38
     * Note that order of returned values must match exactly the order of keys.
39
     * If some entry is not available for given key - it must include null for the missing key.
40
     *
41
     * For example:
42
     * loadKeys(['a', 'b', 'c']) -> ['a' => 'value1, 'b' => null, 'c' => 'value3']
43
     *
44
     * @param array $keys
45
     *
46
     * @return array
47
     * @throws \Exception
48
     */
49
    public function loadKeys(array $keys)
50
    {
51
        if (empty($keys)) {
52
            return $keys;
53
        }
54
55
        $args = [
56
            $this->getWhereParams($keys),
57
        ];
58
59
        $query = $this->getQuery();
60
        $result = $query->get_all($args);
61
        
62
        $loadedItems = [];
63
64
        /**
65
         * Loop over the items and return an array of loaded items,
66
         * where the key is the ID and the value is the Object passed through
67
         * the model layer.
68
         */
69
        foreach ($keys as $key) {
70
            if (isset($result[ $key ])) {
71
                $loadedItems[ $key ] = $result[ $key ];
72
            } else {
73
                $loadedItems[ $key ] = null;
74
            }
75
        }
76
        return $loadedItems;
77
    }
78
}
79