1<?php
2/*
3 * Copyright 2008-2010 GuardTime AS
4 *
5 * This file is part of the GuardTime PHP SDK.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 *     http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20/**
21 * @package asn1
22 */
23
24/**
25 * ASN.1 Boolean implementation.
26 *
27 * @package asn1
28 */
29class ASN1Boolean extends ASN1Object {
30
31    protected $value;
32
33    /**
34     * Constructs a new ASN1Boolean.
35     *
36     * @param  bool $value the value of this boolean, either true or false
37     * @return void
38     */
39    public function __construct($value = null) {
40
41        if (!is_null($value)) {
42
43            if ($value) {
44                $this->value = true;
45
46            } else {
47                $this->value = false;
48
49            }
50
51        }
52
53    }
54
55    /**
56     * Gets the value of this ASN1Boolean.
57     *
58     * @return bool true or false
59     */
60    public function getValue() {
61        return $this->value;
62    }
63
64    /**
65     * Encodes the contents of this ASN1Boolean as DER.
66     *
67     * @return array DER encoding of this ASN1Boolean
68     */
69    public function encodeDER() {
70
71        $bytes = array();
72
73        $this->append($bytes, ASN1DER::encodeType(ASN1_TAG_BOOLEAN));
74        $this->append($bytes, ASN1DER::encodeLength(1));
75
76        if ($this->value) {
77            $this->append($bytes, 0xFF);
78        } else {
79            $this->append($bytes, 0x0);
80        }
81
82        return $bytes;
83    }
84
85    /**
86     * Decodes an ASN1Boolean from the given byte stream.
87     *
88     * @throws GTException
89     * @param  array $bytes V bytes from the encoding of ASN1Boolean TLV
90     * @return void
91     */
92    public function decodeDER($bytes) {
93
94        if (count($bytes) != 1) {
95            throw new GTException("Invalid DER length for ASN1Boolean: " . count($bytes));
96        }
97
98        $byte = $this->readByte($bytes);
99
100        if ($byte == 0xFF) {
101            $this->value = true;
102
103        } else if ($byte == 0x0) {
104            $this->value = false;
105
106        } else {
107            throw new GTException("Invalid byte encoding for ASN1Boolean: " . GTBase16::encode(array($byte)));
108        }
109
110    }
111
112}
113
114?>
115