Skip to content

Commit

Permalink
Merge pull request #50 from xp-forge/feature/conditional
Browse files Browse the repository at this point in the history
Add support for setting the `Last-Modified` header easily
  • Loading branch information
thekid authored Dec 21, 2024
2 parents 93512f5 + fcb0c06 commit c89569c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
18 changes: 18 additions & 0 deletions src/main/php/web/frontend/View.class.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
<?php namespace web\frontend;

use util\Date;
use web\Headers;

/** @test web.frontend.unittest.ViewTest */
class View {
public $template;
Expand Down Expand Up @@ -152,6 +155,21 @@ public function cache($control) {
return $this;
}

/**
* Sets `Last-Modified` to header
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests
* @param ?int|float|string|util.Date $date
* @return self
*/
public function modified($date) {
$this->headers['Last-Modified']= Headers::date(null === $date
? Date::now()
: ($date instanceof Date ? $date : new Date($date))
);
return $this;
}

/**
* Transfers this result
*
Expand Down
21 changes: 20 additions & 1 deletion src/test/php/web/frontend/unittest/ViewTest.class.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
<?php namespace web\frontend\unittest;

use test\{Assert, Test};
use test\{Assert, Test, Values};
use util\Date;
use web\frontend\View;

class ViewTest {

/** @return iterable */
private function modifications() {

// Current date
yield [null, gmdate('D, d M Y H:i:s \G\M\T')];

// Reference date
$date= 'Mon, 25 Nov 2024 19:30:00 GMT';
yield [strtotime($date), $date];
yield [$date, $date];
yield [new Date($date), $date];
}

#[Test]
public function template() {
Assert::equals('test', View::named('test')->template);
Expand Down Expand Up @@ -58,6 +72,11 @@ public function header() {
);
}

#[Test, Values(from: 'modifications')]
public function modified($date, $expected) {
Assert::equals($expected, View::named('test')->modified($date)->headers['Last-Modified']);
}

#[Test]
public function redirect_sets_location_and_status() {
$redirect= View::redirect('http://test');
Expand Down

0 comments on commit c89569c

Please sign in to comment.