From 43c6952c60370889717d3cbe398e0d2faacd5251 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petar=20=C5=A0panja?= Date: Thu, 15 Nov 2018 20:02:47 +0100 Subject: [PATCH] Split Endpoint into Node and Index --- src/lib/SPI/Index.php | 43 ++++++++++++++++++++ src/lib/SPI/Node.php | 94 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 137 insertions(+) create mode 100644 src/lib/SPI/Index.php create mode 100644 src/lib/SPI/Node.php diff --git a/src/lib/SPI/Index.php b/src/lib/SPI/Index.php new file mode 100644 index 0000000..281f3e4 --- /dev/null +++ b/src/lib/SPI/Index.php @@ -0,0 +1,43 @@ +node = $node; + $this->index = $index; + } + + /** + * Return the URL of the Index instance. + * + * @return string + */ + public function getUrl(): string + { + $nodeUrl = $this->node->getUrl(); + + return "{$nodeUrl}/{{$this->index}"; + } +} diff --git a/src/lib/SPI/Node.php b/src/lib/SPI/Node.php new file mode 100644 index 0000000..2da305d --- /dev/null +++ b/src/lib/SPI/Node.php @@ -0,0 +1,94 @@ +scheme = $scheme; + $this->host = $host; + $this->port = $port; + } + + /** + * Return the URL of the Node instance. + * + * @return string + */ + public function getUrl(): string + { + return "{$this->scheme}://{$this->host}:{$this->port}"; + } + + /** + * Build the Node instance from the given $dsn. + * + * Valid DSN is in the form of 'scheme://host:port'. + * + * @param string $dsn + * + * @return \Cabbage\SPI\Node + */ + public static function fromDsn(string $dsn): self + { + $elements = self::parseDsn($dsn); + + return new self( + $elements['scheme'], + $elements['host'], + $elements['port'] + ); + } + + /** + * @param string $dsn + * + * @return mixed[] + */ + private static function parseDsn(string $dsn): array + { + $defaults = [ + 'scheme' => 'http', + 'port' => 9200, + ]; + $elements = parse_url(rtrim($dsn, '/')); + + if ($elements === false) { + throw new RuntimeException( + 'Failed to parse the given DSN' + ); + } + + $elements += $defaults; + + return $elements; + } +}