Skip to content

Commit c1c77fb

Browse files
committed
Add make method to Position instance
1 parent 706d6b0 commit c1c77fb

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

src/Position.php

+19
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Illuminate\Contracts\Support\Arrayable;
66
use Illuminate\Support\Arr;
7+
use Illuminate\Support\Str;
78

89
class Position implements Arrayable
910
{
@@ -87,6 +88,24 @@ class Position implements Arrayable
8788
*/
8889
public ?string $timezone = null;
8990

91+
/**
92+
* Create a new position instance.
93+
*/
94+
public static function make(array $attributes): static
95+
{
96+
$instance = new static;
97+
98+
foreach ($attributes as $key => $value) {
99+
$property = Str::camel($key);
100+
101+
if (property_exists($instance, $property)) {
102+
$instance->{$property} = $value;
103+
}
104+
}
105+
106+
return $instance;
107+
}
108+
90109
/**
91110
* Determine if the position is empty.
92111
*/

tests/PositionTest.php

+39-1
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,50 @@
22

33
namespace Stevebauman\Location\Tests;
44

5+
use Illuminate\Support\Arr;
56
use Stevebauman\Location\Position;
67

8+
it('can be created with attributes array', function (array $attributes, array $expected) {
9+
$position = Position::make($attributes);
10+
11+
expect(Arr::only($position->toArray(), array_keys($expected)))->toBe($expected);
12+
})->with([
13+
// Camel casing attributes:
14+
[
15+
[
16+
'ip' => '127.0.0.1',
17+
'driver' => 'local',
18+
'countryName' => 'foo',
19+
'countryCode' => 'bar',
20+
],
21+
[
22+
'ip' => '127.0.0.1',
23+
'driver' => 'local',
24+
'countryName' => 'foo',
25+
'countryCode' => 'bar',
26+
]
27+
],
28+
// Snake casing attributes:
29+
[
30+
[
31+
'ip' => '127.0.0.1',
32+
'driver' => 'local',
33+
'country_name' => 'foo',
34+
'country_code' => 'bar',
35+
],
36+
[
37+
'ip' => '127.0.0.1',
38+
'driver' => 'local',
39+
'countryName' => 'foo',
40+
'countryCode' => 'bar',
41+
]
42+
]
43+
]);
44+
745
it('returns empty', function () {
846
$position = new Position();
947

10-
$position->ip = '192.168.1.1';
48+
$position->ip = '127.0.0.1';
1149
$position->driver = 'foo';
1250

1351
expect($position->isEmpty())->toBeTrue();

0 commit comments

Comments
 (0)