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

    protected $objects = array();

    /**
     * Constructs a new ASN1Sequence instance.
     *
     */
    public function __construct() {
    }

    /**
     * Adds a new object to this sequence.
     *
     * @param  ASN1Object $object
     * @return void
     */
    public function add($object) {
        array_push($this->objects, $object);
    }

    /**
     * Gets the object at index.
     *
     * @param  $index 0 based index
     * @return ASN1Object object at index
     */
    public function getObjectAt($index) {
        return $this->objects[$index];
    }

    /**
     * Gets the number of objects stored inside this sequence.
     *
     * @return int object count
     */
    public function getObjectCount() {
        return count($this->objects);
    }

    /**
     * Gets all objects stored inside this sequence.
     *
     * @return array stored objects
     */
    public function getObjects() {
        return $this->objects;
    }

    /**
     * Encodes this sequence and the objects stored to DER byte array.
     *
     * @return array DER encoding of this sequence
     */
    public function encodeDER() {

        $bytes = array();

        foreach ($this->objects as $object) {
            $this->append($bytes, $object->encodeDER());
        }

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

        return $bytes;
    }

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

        while (count($bytes) > 0) {

            $object = ASN1DER::decodeType($bytes);
            $length = ASN1DER::decodeLength($bytes);

            $object->decodeDER($this->readBytes($bytes, $length));

            array_push($this->objects, $object);
        }

    }
}

?>
