Exemplo n.º 1
0
 /**
  * Generates archive of documents based on specified data.
  *
  * @param array  $data array where each element is data for one document
  * @param string $path where to save generated archive
  * @param Converter $converter OPTIONAL document converter
  */
 public function generateArchive($data, $path, $converter = null)
 {
     //Files to be deleted after creating archive
     $cleanup = array();
     //Create directory if nonexistent
     @mkdir(dirname($path), 0770, true);
     //Prepare result archive
     $archive = new \ZipArchive();
     if (!$archive->open($path, \ZipArchive::CREATE)) {
         throw new \Exception("Failed to open result archive.");
     }
     //Create documents and add them to archive
     foreach ($data as $index => $docdata) {
         $ext = $this->template->getExtension();
         //Generate file
         $file = "{$this->tmp}/document{$index}.{$ext}";
         $document = $this->generate($docdata);
         //Convert if needed
         if ($converter) {
             $converter->save($document, $file);
             $ext = $converter->getExtension();
         } else {
             $document->save($file);
         }
         //Remove this file after we're done
         $cleanup[] = $file;
         //Put to archive
         $archive->addFile($file, "document{$index}.{$ext}");
     }
     //Write documents to archive
     $archive->close();
     //Remove temp files, has to be done after closing archive
     foreach ($cleanup as $file) {
         unlink($file);
     }
     //Check if archive was really created
     if (!file_exists($path)) {
         throw new \Exception("Failed to create result archive.");
     }
 }