UtilsTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 16
dl 0
loc 57
rs 10
c 2
b 1
f 0
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getOptions() 0 25 3
A processRow() 0 12 3
1
<?php
2
3
namespace Jidaikobo\Kontiki\Models\BaseModelTraits;
4
5
trait UtilsTrait
6
{
7
    /**
8
     * Get options in the form of id => field value, excluding a specific ID.
9
     *
10
     * @param string $fieldName The field name to use as the value.
11
     * @param bool $includeEmpty Whether to include an empty option at the start.
12
     * @param string $emptyLabel The label for the empty option (default: '').
13
     * @param int|null $excludeId The ID to exclude from the results (default: null).
14
     * @return array Associative array of id => field value.
15
     */
16
    public function getOptions(
17
        string $fieldName,
18
        bool $includeEmpty = false,
19
        string $emptyLabel = '',
20
        ?int $excludeId = null
21
    ): array {
22
        $query = $this->db->table($this->table)->select(['id', $fieldName]);
23
24
        if ($excludeId !== null) {
25
            $query->where('id', '!=', $excludeId);
26
        }
27
28
        $results = $query->get();
29
30
        $options = array_column(
31
            array_map(fn($row) => $this->processRow($row, $fieldName), $results->toArray()),
32
            1,
33
            0
34
        );
35
36
        if ($includeEmpty) {
37
            $options = ['' => $emptyLabel] + $options;
38
        }
39
40
        return $options;
41
    }
42
43
    /**
44
     * Process a row of data before retrieving.
45
     *
46
     * @param object $row The database row object.
47
     * @param string $fieldName The field name to extract.
48
     * @return mixed The processed field value.
49
     */
50
    private function processRow(object $row, string $fieldName)
51
    {
52
        if (!isset($row->id, $row->$fieldName)) {
53
            return null;
54
        }
55
56
        $processedRow = (array)$row;
57
        if (method_exists($this, 'processDataBeforeGet')) {
58
            $processedRow = $this->processDataBeforeGet($processedRow);
59
        }
60
61
        return [$row->id, $processedRow[$fieldName]];
62
    }
63
}
64