<?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
 */

/**
 * ASN.1 Integer implementation.
 *
 * @package asn1
 */
class ASN1Integer extends ASN1Object {

    protected $value;

    /**
     * Constructs a new ASN1Integer.
     *
     * @throws GTException
     * @param  int|GTBigInteger $value integer or GTBigInteger instance
     * @return void
     */
    public function __construct($value = null) {

        if (!is_null($value)) {

            if (is_integer($value)) {
                $this->value = new GTBigInteger($value);

            } else if ($value instanceof GTBigInteger) {
                $this->value = $value;

            } else {
                throw new GTException("value must be an int or GTBigInteger");
            }
        }
    }

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

    /**
     * Encodes the contents of this ASN1Integer as DER.
     *
     * @return array DER encoding of this ASN1Integer
     */
    public function encodeDER() {

        $bytes = $this->value->toBytes();

        if ($this->value->comp(new GTBigInteger(0)) == -1) {

            while (count($bytes) > 0) {

                if ($bytes[0] == 0x0) {
                    array_shift($bytes);

                } else {
                    break;

                }
            }

            if ($bytes[0] >> 7 == 1) {
                array_unshift($bytes, 0xFF);

            } else {
                $bytes[0] = ($bytes[0] | 0x80) & 0xFF;

            }
        }

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

        return $bytes;
    }

    /**
     * Decodes an ASN1 Integer from the given byte stream.
     *
     * @param  array $bytes V bytes from the encoding of ASN1Integer TLV.
     * @return void
     */
    public function decodeDER($bytes) {

        $this->value = new GTBigInteger($bytes);

    }

}

?>
