Completed
Branch dms-n-gql-tweaks (3cbb1d)
by
unknown
60:42 queued 51:59
created

Utilities::sanitizeWhereArgs()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
nc 8
nop 3
dl 0
loc 26
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
namespace EventEspresso\core\domain\services\graphql;
4
5
use GraphQLRelay\Relay;
6
7
class Utilities
8
{
9
    /**
10
     * This sets up the "allowed" args, and translates the GraphQL-friendly keys to model
11
     * friendly keys.
12
     *
13
     * @param array $where_args
14
     * @param array $arg_mapping
15
     * @param array $id_fields The fields to convert from global IDs to DB IDs.
16
     * @return array
17
     */
18
    public function sanitizeWhereArgs(array $where_args, array $arg_mapping, array $id_fields)
19
    {
20
        $where_params = [];
21
        foreach ($where_args as $arg => $value) {
22
            if (! array_key_exists($arg, $arg_mapping)) {
23
                continue;
24
            }
25
            if (is_array($value) && ! empty($value)) {
26
                $value = array_map(
27
                    static function ($value) {
28
                        if (is_string($value)) {
29
                            $value = sanitize_text_field($value);
30
                        }
31
                        return $value;
32
                    },
33
                    $value
34
                );
35
            } elseif (is_string($value)) {
36
                $value = sanitize_text_field($value);
37
            }
38
            $where_params[ $arg_mapping[ $arg ] ] = in_array($arg, $id_fields, true)
39
                ? $this->convertGlobalId($value)
40
                : $value;
41
        }
42
        return $where_params;
43
    }
44
45
46
    /**
47
     * Converts global ID to DB ID.
48
     *
49
     * @param string|string[] $ID
50
     * @return mixed
51
     */
52
    protected function convertGlobalId($ID)
53
    {
54
        if (is_array($ID)) {
55
            return array_map([$this, 'convertGlobalId'], $ID);
56
        }
57
        $parts = Relay::fromGlobalId($ID);
58
        return ! empty($parts['id']) ? $parts['id'] : null;
59
    }
60
}
61