Skip to content

Instantly share code, notes, and snippets.

@wallacemaxters
Last active August 29, 2015 14:26
Show Gist options
  • Save wallacemaxters/04a85d267a2106d202ce to your computer and use it in GitHub Desktop.
Save wallacemaxters/04a85d267a2106d202ce to your computer and use it in GitHub Desktop.
PHP solution for fixed strings length
<?php
/**
* @author Wallace de Souza Vizerra <wallacemaxters@gmail.com>
* @version 1.0
* @see hehehehehe
**/
final class FixedString implements ArrayAccess
{
/**
* @var string
**/
protected $text;
/**
* @var string
* The encoding of string
* */
protected $encoding;
/**
* @var int
**/
protected $length;
/**
* @param string $text
* @param int $length
* @param null|string $encoding
**/
public function __construct($text, $length, $encoding = null)
{
$this->encoding = $encoding ?: mb_internal_encoding();
if (is_object($text) && method_exists($text, '__toString')) {
$text = (string) $text;
} elseif ( ! is_string($text)) {
$message = sprintf('The first argument should be a string, %s given', gettype($text));
throw new InvalidArgumentException($message);
}
$this->length = $length;
$this->text = str_pad(mb_substr((string) $text, 0, $this->length, $this->encoding), $this->length);
}
/**
* @return int
**/
public function getLength()
{
return $this->length;
}
/**
* Returns the string lenght accordding to encoding
* @return int
**/
public function getEncodedLength()
{
return mb_strlen($this->text, $this->encoding);
}
/**
* Get encoding of string
* @return string
**/
public function getEncoding()
{
return $this->encoding;
}
/**
* Convert this object in to string
* */
public function __toString()
{
return $this->text;
}
/**
* Implementation of \ArrayAccess interface
* @return string
* */
public function offsetGet($index)
{
return mb_substr($this->text, $index, 1, $this->encoding);
}
/**
* @param int $index
* @param string $value
* @return void
* */
public function offsetSet($index, $value)
{
if ($index > $this->getEncodedLength()) {
throw new OutOfRangeException('Out of Range!');
}
// Não existe mb_substr_replace :\
// mb_substr_replace doesn't exists :\
$text = mb_substr($this->text, 0, $index, $this->encoding)
. $value
. mb_substr($this->text, $index + 1, $this->getLength(), $this->encoding);
$this->text = $text;
}
/**
* @param int $index
* @return void
* */
public function offsetUnset($index)
{
$this->offsetSet($index, ' ');
}
/**
* @param int $index
* @return boolean
**/
public function offsetExists($index)
{
return $this->offsetGet($index) != '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment