-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayUtilsTrait.php
More file actions
112 lines (94 loc) · 2.28 KB
/
ArrayUtilsTrait.php
File metadata and controls
112 lines (94 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
namespace SyncEngine\Structure\Data\Trait;
trait ArrayUtilsTrait
{
abstract function getArrayCopy(): array;
public static function data( mixed $resource = [] ): mixed
{
return $resource instanceof \ArrayObject ? $resource->getArrayCopy() : $resource;
}
public static function values( array|\ArrayObject $resource = [] ): array
{
return array_values( static::data( $resource ) );
}
public static function keys( array|\ArrayObject $resource = [] ): array
{
return array_keys( static::data( $resource ) );
}
public function isEmpty(): bool
{
return empty( static::data( $this ) );
}
public function hasValues(): bool
{
$data = static::data( $this );
if ( ! is_iterable( $data ) ) {
return ! empty( $data );
}
foreach ( $data as $value ) {
if ( ! empty( $value ) || is_numeric( $value ) || is_bool( $value ) ) {
return true;
}
}
return false;
}
public function isList(): bool
{
return array_is_list( $this->getArrayCopy() );
}
/**
* @param int $size
* @param bool $preserve_keys
*
* @return static[]
*/
public function chunk( int $size, $preserve_keys = true ): array
{
$chunks = array_chunk( $this->getArrayCopy(), $size, $preserve_keys );
return array_map( fn( $chunk ) => new static( $chunk ), $chunks );
}
/**
* @param int $offset
* @param int $length
* @param bool $preserve_keys
*
* @return static
*/
public function slice( int $offset, int $length, $preserve_keys = true ): static
{
return new static( array_slice( $this->getArrayCopy(), $offset, $length, $preserve_keys ) );
}
/**
* @param callable|null $callback
* @param int $mode
*
* @return static
*/
public function filter( ?callable $callback = null, int $mode = 0 ): static
{
return new static( array_filter( $this->getArrayCopy(), $callback, $mode ) );
}
/**
* @param int $flags
*
* @return $this
*/
public function unique( $flags = SORT_REGULAR ): static
{
return new static( array_unique( $this->getArrayCopy(), $flags ) );
}
/**
* @return $this
*/
public function list(): static
{
return new static( static::values( $this ) );
}
public function usort( ?callable $callback = null ): static
{
$list = $this->get();
usort( $list, $callback );
$this->set( $list );
return $this;
}
}