DownloadFormat.php
1 <?php
2 /**
3  * wCMF - wemove Content Management Framework
4  * Copyright (C) 2005-2020 wemove digital solutions GmbH
5  *
6  * Licensed under the terms of the MIT License.
7  *
8  * See the LICENSE file distributed with this work for
9  * additional information.
10  */
12 
16 
17 /**
18  * DownloadFormat is used for downloads. It will be automatically chosen, if
19  * a file is set using the Response::setFile() method.
20  *
21  * @author ingo herwig <ingo@wemove.com>
22  */
24 
25  /**
26  * @see Format::getMimeType()
27  */
28  public function getMimeType(Response $response=null) {
29  return 'application/octet-stream';
30  }
31 
32  /**
33  * @see Format::isCached()
34  */
35  public function isCached(Response $response) {
36  $cacheDate = $this->getCacheDate($response);
37  if ($cacheDate === null) {
38  return false;
39  }
40  $cacheLifetime = $response->getCacheLifetime();
41  $expireDate = null;
42  if ($cacheLifetime !== null && $cacheDate !== null) {
43  $expireDate = clone $cacheDate;
44  $expireDate->modify('+'.$cacheLifetime.' seconds');
45  }
46  return $expireDate === null || $expireDate < new \DateTime();
47  }
48 
49  /**
50  * @see Format::getCacheDate()
51  */
52  public function getCacheDate(Response $response) {
53  $file = $response->getFile();
54  return $file && file_exists($file['filename']) ?
55  \DateTime::createFromFormat('U', filemtime($file['filename'])) : null;
56  }
57 
58  /**
59  * @see Format::getResponseHeaders()
60  */
61  public function getResponseHeaders(Response $response) {
62  $file = $response->getFile();
63  if ($file) {
64  $response->setHeader("Content-Type", $file['type']);
65  if ($file['isDownload']) {
66  $response->setHeader("Content-Disposition", 'attachment; filename="'.basename($file['filename']).'"');
67  }
68  }
69  return $response->getHeaders();
70  }
71 
72  /**
73  * @see AbstractFormat::deserializeValues()
74  */
75  protected function deserializeValues(Request $request) {
76  return $request->getValues();
77  }
78 
79  /**
80  * @see AbstractFormat::serializeValues()
81  */
82  protected function serializeValues(Response $response) {
83  $file = $response->getFile();
84  if ($file) {
85  echo $file['content'];
86  }
87  return $response->getValues();
88  }
89 }
90 ?>
Response holds the response values that are used as output from Controller instances.
Definition: Response.php:20
Request holds the request values that are used as input to Controller instances.
Definition: Request.php:18
getValues()
Get all key value pairs.
getFile()
Get the file download.
Format defines the interface for all format classes.
Definition: Format.php:25
DownloadFormat is used for downloads.
getCacheLifetime()
Get the lifetime of a cached response.
AbstractFormat is used as base class for specialized formats.
setHeader($name, $value)
Set a header value.