Skip to content

Commit

Permalink
Coordindate serialize.
Browse files Browse the repository at this point in the history
  • Loading branch information
dereuromark committed Feb 26, 2024
1 parent 840bd2c commit d91c76b
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
37 changes: 35 additions & 2 deletions src/Geocoder/GeoCoordinate.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

namespace Geo\Geocoder;

class GeoCoordinate implements \Stringable {
use InvalidArgumentException;
use JsonSerializable;
use Stringable;

class GeoCoordinate implements JsonSerializable, Stringable {

protected float $latitude;

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

/**
* @param string $coordinate
*
* @return static
*/
public static function fromString(string $coordinate): static {
if (!str_contains($coordinate, ',')) {
throw new InvalidArgumentException('Coordinate must be in format: lat,lng');
}

[$lat, $lng] = explode(',', $coordinate);

return new static($lat, $lng);
}

/**
* @return string
*/
public function __toString(): string {
public function toString(): string {
return $this->latitude . ',' . $this->longitude;
}

/**
* @return string
*/
public function __toString(): string {
return $this->toString();
}

/**
* @return string
*/
public function jsonSerialize(): string {
return $this->toString();
}

}
30 changes: 30 additions & 0 deletions tests/TestCase/Geocoder/GeoCoordinateTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace Geo\Test\Geocoder;

use Cake\TestSuite\TestCase;
use Geo\Geocoder\GeoCoordinate;

class GeoCoordinateTest extends TestCase {

/**
* @return void
*/
public function testSerialize() {
$geoCoordinate = new GeoCoordinate(25.43, 12.22);
$result = json_encode($geoCoordinate);

$this->assertSame('"25.43,12.22"', $result);
}

/**
* @return void
*/
public function testDeserialize() {
$coordinate = json_decode('"25.43,12.22"', true);
$result = GeoCoordinate::fromString($coordinate);

$this->assertSame('25.43,12.22', (string)$result);
}

}

0 comments on commit d91c76b

Please sign in to comment.