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

    protected $objects = array();

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

    /**
     * Adds an ASN1Object to this set.
     *
     * @param  ASN1Object $object the object to add
     * @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 set.
     *
     * @return int the number of objects
     */
    public function getObjectCount() {
        return count($this->objects);
    }

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

    /**
     * Encodes this ASN1Set and the objects contained within to DER.
     *
     * @return array DER encoding of this ASN1Set
     */
    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_SET));

        return $bytes;
    }

    /**
     * Decodes an ASN1Set from the given byte stream.
     *
     * @param  $bytes V bytes from the encoding of ASN1Set 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);
        }

    }
}

?>
