<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\HTML;

use Kufer\Web\Classes\Stream\ArrayStream;

class TextToHtmlConverter implements \Kufer\Web\Classes\Converter\TextConverter, \Kufer\Web\Classes\Converter\HTMLConverter
{
  private $text;

  public function __construct(string $text)
  {
    $this->text = $text;
  }

  public function toText(): string
  {
    return $this->text;
  }

  public function toHTML(): string
  {
    $text = str_replace("\r\n", "\n", $this->text);

    return (new ArrayStream(explode("\n", $text)))
      ->map(static function(string $line): string {
        $trimmed = trim($line);
        if ($trimmed === '') {
          return '';
        }

        return $line;
      })
      ->map(static function(string $line): string {
        if ($line === '') {
          return '<br/>';
        }

        return '<p>' . \StringOperations::htmlentities($line) . '</p>';
      })
      ->implode("\n");
  }
}