<?php
/*
 * Copyright 2008-2010 GuardTime AS
 *
 * This file is part of the GuardTime PHP SDK.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @package asn1
 */

/**
 * Generic base class for ASN.1 String types.
 *
 * @package asn1
 */
abstract class ASN1String extends ASN1Object {

    protected $value;

    /**
     * Constructs a new instance of ASN1String.
     *
     * @param  string $value
     */
    public function __construct($value = null) {

        if (!is_null($value)) {
            $this->setValue($value);
        }

    }

    /**
     * Encodes the contents of this ASN1String.
     *
     * @return array DER encoding for this string
     */
    public function encodeDER() {

        $bytes = GTUtil::toByteArray($this->value);

        $this->prepend($bytes, ASN1DER::encodeLength(count($bytes)));
        $this->prepend($bytes, ASN1DER::encodeType($this->getType()));

        return $bytes;
    }

    /**
     * Decodes an ASN1String from the given byte stream.
     *
     * @param  $bytes V bytes of this ASN1String TLV
     * @return void
     */
    public function decodeDER($bytes) {
        $this->setValue(GTUtil::fromByteArray($bytes));
    }

    /**
     * Sets the value of this ASN1String.
     *
     * @param  string $value
     * @return void
     */
    protected function setValue($value) {
        $this->value = $value;
    }

    /**
     * Gets the value of this ASN1String.
     *
     * @return string
     */
    public function getValue() {
        return $this->value;
    }

    /**
     * Gets the actual ASN.1 type to use for encoding/decoding this ASN1String.
     * @abstract
     * @return int
     */
    protected abstract function getType();

}

?>
