<?php
/**
 * Copyright 2008-2017 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file LICENSE for license information (LGPL). If you
 * did not receive this file, see http://www.horde.org/licenses/lgpl21.
 *
 * @author   Chuck Hagenbuch <chuck@horde.org>
 * @author   Jan Schneider <jan@horde.org>
 * @category Horde
 * @license  http://www.horde.org/licenses/lgpl21 LGPL
 * @package  Date_Parser
 */

/**
 *
 *
 * @author    Chuck Hagenbuch <chuck@horde.org>
 * @author    Jan Schneider <jan@horde.org>
 * @category  Horde
 * @copyright 2008-2017 Horde LLC
 * @license   http://www.horde.org/licenses/lgpl21 LGPL
 * @package   Date_Parser
 */
class Horde_Date_Parser_Token
{
    public $word;
    public $tags;

    public function __construct($word)
    {
        $this->word = $word;
        $this->tags = array();
    }

    /**
     * Tag this token with the specified tag
     */
    public function tag($tagClass, $tag)
    {
        $this->tags[] = array($tagClass, $tag);
    }

    /**
     * Remove all tags of the given class
     */
    public function untag($tagClass)
    {
        $this->tags = array_filter(
            $this->tags,
            function ($t) use ($tagClass) {
                return substr($t[0], 0, strlen($tagClass)) != $tagClass;
            }
        );
    }

    /**
     * Return true if this token has any tags
     */
    public function tagged()
    {
        return count($this->tags) > 0;
    }

    /**
     * Return the Tag that matches the given class
     */
    public function getTag($tagClass)
    {
        $matches = array_filter(
            $this->tags,
            function ($t) use ($tagClass) {
                return substr($t[0], 0, strlen($tagClass)) == $tagClass;
            }
        );
        $match = array_shift($matches);
        return (is_array($match) ? $match[1] : null);
    }

    /**
     * Print this Token in a pretty way
     */
    public function __toString()
    {
        $tags = array();
        foreach ($this->tags as $t) {
            $tags[] = implode(': ', $t);
        }
        return '(' . implode(', ', $tags) . ') ';
    }

}
