Skip to content

Commit

Permalink
Add get method to CharacterCollection + add Exception + update PHPDocs
Browse files Browse the repository at this point in the history
  • Loading branch information
jeroendesloovere committed Apr 3, 2018
1 parent 31b8b7a commit 49cf48a
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 34 deletions.
16 changes: 2 additions & 14 deletions src/Character.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,22 @@ class Character
/** @var array */
private $positions;

/**
* @param string $value
*/
public function __construct(string $value)
{
$this->value = $value;
}

/**
* @param int $position
*/
public function addPosition(int $position)
{
$this->positions[] = $position;
}

/**
* @return array
*/
public function getPositions()
public function getPositions(): array
{
return $this->positions;
}

/**
* @return string
*/
public function getValue()
public function getValue(): string
{
return $this->value;
}
Expand Down
39 changes: 19 additions & 20 deletions src/CharacterCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ class CharacterCollection
/** @var array */
private $characters;

/**
* @param string $sentence
*/
public function __construct(string $sentence)
{
/** @var array $characters */
Expand All @@ -20,11 +17,21 @@ public function __construct(string $sentence)
}
}

/**
* @param int $position
* @param string $character
*/
public function add(int $position, string $character)
public function __toString(): string
{
$sentences = [];
foreach ($this->characters as $position => $character) {
foreach ($character->getPositions() as $position) {
$sentences[$position] = $character->getValue();
}
}

ksort($sentences);

return implode($sentences);
}

public function add(int $position, string $character): void
{
if ($character === '') {
return;
Expand All @@ -37,20 +44,12 @@ public function add(int $position, string $character)
$this->characters[$character]->addPosition($position);
}

/**
* @return string
*/
public function __toString(): string
public function get(string $character): Character
{
$sentences = [];
foreach ($this->characters as $position => $character) {
foreach ($character->getPositions() as $position) {
$sentences[$position] = $character->getValue();
}
if (!array_key_exists($character, $this->characters)) {
throw Exception::characterNotFound($character);
}

ksort($sentences);

return implode($sentences);
return $this->characters[$character];
}
}
11 changes: 11 additions & 0 deletions src/Exception.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace JeroenDesloovere\CharacterCollection;

class Exception extends \Exception
{
public static function characterNotFound(string $character): \Exception
{
return new self('Character ' . $character . ' not found.');
}
}

0 comments on commit 49cf48a

Please sign in to comment.