<?php

namespace Drupal\miniorange_saml;

/**
 * Class for SAML2 Response messages.
 */
class Saml2Response {
  /**
   * The assertions in this response.
   *
   * @var array
   */
  private $assertions;

  /**
   * The destination URL in this response.
   *
   * @var string
   */
  private $destination;

  /**
   * A list of certificates used for signing or encryption.
   *
   * @var string[]
   */
  private $certificates;

  /**
   * The signature data for the response.
   *
   * @var string|null
   */
  private $signatureData;

  /**
   * Constructor for SAML 2 response messages.
   *
   * @param \DOMElement|null $xml
   *   The input message.
   */
  public function __construct(?\DOMElement $xml = NULL) {
    // parent::__construct('Response', $xml);.
    $this->assertions = [];
    $this->certificates = [];
    if ($xml === NULL) {
      return;
    }

    $sig = Utilities::validateElement($xml);
    if ($sig !== FALSE) {
      $this->certificates = $sig['Certificates'];
      $this->signatureData = $sig;
    }

    /* set the destination from saml response */
    if ($xml->hasAttribute('Destination')) {
      $this->destination = $xml->getAttribute('Destination');
    }

    for ($node = $xml->firstChild; $node !== NULL; $node = $node->nextSibling) {
      if ($node->namespaceURI !== 'urn:oasis:names:tc:SAML:2.0:assertion') {
        continue;
      }

      if ($node->localName === 'Assertion' || $node->localName === 'EncryptedAssertion') {
        $this->assertions[] = new Saml2Assertion($node);
      }
    }
  }

  /**
   * Retrieve the assertions in this response.
   *
   * @return Saml2Assertion[]
   *   assertions
   */
  public function getAssertions() {
    return $this->assertions;
  }

  /**
   * Retrieve the destination in the response.
   *
   * @return string
   *   The destination URL or URI of the SAML response.
   */
  public function getDestination() {
    return $this->destination;
  }

  /**
   * Retrieves the signature data.
   *
   * @return string|null
   *   The signature data in string format or null if no signature is present.
   */
  public function getSignatureData() {
    return $this->signatureData;
  }

}
