<?php

/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

class ZipAPI
{
  public static function readZipFile($pFilename)
  {
    if (!static::isZipAvailable()) {
      throw new Exception('Zip Features not available on this server');
    }

    if (self::doesZipArchivClassExist()) {
      return static::readZipFileNew($pFilename);
    }

    $result = '';
    $zipArchive = zip_open($pFilename);

    if (is_resource($zipArchive)) {
      $zipEntry = zip_read($zipArchive); 
      

      if (zip_entry_open($zipArchive, $zipEntry, 'r')) {
        $result = zip_entry_read($zipEntry, zip_entry_filesize($zipEntry));

        zip_entry_close($zipEntry);
      }
      zip_close($zipArchive);
    }

    return $result;
  }

  protected static function doesZipArchivClassExist()
  {
    static $cache = null;
    if (\is_null($cache)) {
      $cache = \class_exists('\\ZipArchive');
    }

    return $cache;
  }

  protected static function readZipFileNew($pFilename)
  {
    $za = new ZipArchive();
    $code = $za->open($pFilename);
    if ($code !== true) {
      throw new \Exception('Could not open ZIP-File ' . $pFilename . ' (Code ' . $code . ')');
    }

    return $za->getFromIndex(0);
  }

  public static function isZipAvailable()
  {
    return self::doesZipArchivClassExist() || function_exists('zip_open');
  }
}