Skip to content

Commit d91c76b

Browse files
committed
Coordindate serialize.
1 parent 840bd2c commit d91c76b

File tree

2 files changed

+65
-2
lines changed

2 files changed

+65
-2
lines changed

src/Geocoder/GeoCoordinate.php

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22

33
namespace Geo\Geocoder;
44

5-
class GeoCoordinate implements \Stringable {
5+
use InvalidArgumentException;
6+
use JsonSerializable;
7+
use Stringable;
8+
9+
class GeoCoordinate implements JsonSerializable, Stringable {
610

711
protected float $latitude;
812

@@ -55,11 +59,40 @@ public static function fromArray(array $data): static {
5559
return new static($lat, $lng);
5660
}
5761

62+
/**
63+
* @param string $coordinate
64+
*
65+
* @return static
66+
*/
67+
public static function fromString(string $coordinate): static {
68+
if (!str_contains($coordinate, ',')) {
69+
throw new InvalidArgumentException('Coordinate must be in format: lat,lng');
70+
}
71+
72+
[$lat, $lng] = explode(',', $coordinate);
73+
74+
return new static($lat, $lng);
75+
}
76+
5877
/**
5978
* @return string
6079
*/
61-
public function __toString(): string {
80+
public function toString(): string {
6281
return $this->latitude . ',' . $this->longitude;
6382
}
6483

84+
/**
85+
* @return string
86+
*/
87+
public function __toString(): string {
88+
return $this->toString();
89+
}
90+
91+
/**
92+
* @return string
93+
*/
94+
public function jsonSerialize(): string {
95+
return $this->toString();
96+
}
97+
6598
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
namespace Geo\Test\Geocoder;
4+
5+
use Cake\TestSuite\TestCase;
6+
use Geo\Geocoder\GeoCoordinate;
7+
8+
class GeoCoordinateTest extends TestCase {
9+
10+
/**
11+
* @return void
12+
*/
13+
public function testSerialize() {
14+
$geoCoordinate = new GeoCoordinate(25.43, 12.22);
15+
$result = json_encode($geoCoordinate);
16+
17+
$this->assertSame('"25.43,12.22"', $result);
18+
}
19+
20+
/**
21+
* @return void
22+
*/
23+
public function testDeserialize() {
24+
$coordinate = json_decode('"25.43,12.22"', true);
25+
$result = GeoCoordinate::fromString($coordinate);
26+
27+
$this->assertSame('25.43,12.22', (string)$result);
28+
}
29+
30+
}

0 commit comments

Comments
 (0)