<?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 Boolean implementation.
 *
 * @package asn1
 */
class ASN1Boolean extends ASN1Object {

    protected $value;

    /**
     * Constructs a new ASN1Boolean.
     *
     * @param  bool $value the value of this boolean, either true or false
     * @return void
     */
    public function __construct($value = null) {

        if (!is_null($value)) {

            if ($value) {
                $this->value = true;

            } else {
                $this->value = false;

            }

        }

    }

    /**
     * Gets the value of this ASN1Boolean.
     *
     * @return bool true or false
     */
    public function getValue() {
        return $this->value;
    }

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

        $bytes = array();

        $this->append($bytes, ASN1DER::encodeType(ASN1_TAG_BOOLEAN));
        $this->append($bytes, ASN1DER::encodeLength(1));

        if ($this->value) {
            $this->append($bytes, 0xFF);
        } else {
            $this->append($bytes, 0x0);
        }

        return $bytes;
    }

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

        if (count($bytes) != 1) {
            throw new GTException("Invalid DER length for ASN1Boolean: " . count($bytes));
        }

        $byte = $this->readByte($bytes);

        if ($byte == 0xFF) {
            $this->value = true;

        } else if ($byte == 0x0) {
            $this->value = false;

        } else {
            throw new GTException("Invalid byte encoding for ASN1Boolean: " . GTBase16::encode(array($byte)));
        }

    }

}

?>
