Skip to content

Commit

Permalink
Split Endpoint into Node and Index
Browse files Browse the repository at this point in the history
  • Loading branch information
pspanja committed Nov 15, 2018
1 parent 37353c9 commit 43c6952
Show file tree
Hide file tree
Showing 2 changed files with 137 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/lib/SPI/Index.php
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

namespace Cabbage\SPI;

/**
* Defines access to an Elasticsearch index.
*/
final class Index
{
/**
* @var \Cabbage\SPI\Node
*/
public $node;

/**
* @var string
*/
public $index;

/**
* @param \Cabbage\SPI\Node $node
* @param string $index
*/
public function __construct(Node $node, string $index)
{
$this->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}";
}
}
94 changes: 94 additions & 0 deletions src/lib/SPI/Node.php
@@ -0,0 +1,94 @@
<?php

declare(strict_types=1);

namespace Cabbage\SPI;

use RuntimeException;

/**
* Defines access to an Elasticsearch node.
*/
final class Node
{
/**
* @var string
*/
public $scheme;

/**
* @var string
*/
public $host;

/**
* @var int
*/
public $port;

/**
* @param string $scheme
* @param string $host
* @param int $port
*/
public function __construct(string $scheme, string $host, int $port)
{
$this->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;
}
}

0 comments on commit 43c6952

Please sign in to comment.