<?php

/**
 * Classe stringa (immutabile)
 * @author p6
 */
class Stringa
{
  /**
   * @var string
   */
  private $value;
    
  /**
   * @var int
   */
  private $length;
    
  /**
   * @param mixed $val
   */
  public function __construct($val = null)
  {
    $this->value = (string)$val;
    $this->length = strlen($this->value);
  }
  
  /**
   * @return int strlen
   */
  public function length()
  {
    return $this->length;
  }
  
  /**
   * @param string $str
   * @param int $offset default=null
   * @param bool $ignoreCase default=false
   */
  public function indexOf($str, $offset=null, $ignoreCase=false)
  {
    $pos = $ignoreCase ? stripos : strpos;
    $index = $pos($this, $str, $offset);
    return $index === false ? -1 : $index;    
  }
  
  /**
   * @return string
   */
  public function __toString()
  {
    return $this->value;
  }

  /**
   * @return Stringa
   */
  public function toLower()
  {
    return new Stringa(strtolower($this));
  }

  /**
   * @return Stringa
   */
  public function toUpper()
  {
    return new Stringa(strtoupper($this));
  }
  
  /**
   * 
   * @param string $str
   * @param bool $ignoreCase
   * @return int < 0 if this is less than str; > 0 if this is greater than str, and 0 if they are equal. 
   */
  public function compareTo($str, $ignoreCase=false)
  {
    $cmp = $ignoreCase ? strcasecmp : strcmp;
    return $cmp($this, $str);
  }
  
  /**
   * @param string $pattern
   * @param int $limit
   * @return Stringa[]
   */
  public function split($pattern, $limit=null)
  {
    $chunks = split($pattern, $this, $limit);
    if($chunks === false)
      return false;
    $strings = array();
    foreach($chunks as $item)
      $strings[] = new Stringa($item);
    return $strings;
  }
}
