Skip to content

Commit 16b27a8

Browse files
authored
Merge pull request #3 from php-etl/feature/add-date-functions
feature/add-date-functions : add date functions
2 parents 7b0ba90 + 0b7cf41 commit 16b27a8

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

src/DateTime.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Kiboko\Component\StringExpressionLanguage;
6+
7+
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
8+
9+
class DateTime extends ExpressionFunction
10+
{
11+
public function __construct($name)
12+
{
13+
parent::__construct(
14+
$name,
15+
\Closure::fromCallable([$this, 'compile'])->bindTo($this),
16+
\Closure::fromCallable([$this, 'evaluate'])->bindTo($this)
17+
);
18+
}
19+
20+
private function compile(string $date, string $format, string $timezone = null)
21+
{
22+
return <<<"PHP"
23+
\\DateTimeImmutable::createFromFormat({$format}, {$date}, {$timezone} !== null ? new \\DateTimeZone({$timezone}) : null)
24+
PHP;
25+
}
26+
27+
private function evaluate(array $context, string $date, string $format, string $timezone = null)
28+
{
29+
return \DateTimeImmutable::createFromFormat($format,$date, $timezone !== null ? new \DateTimeZone($timezone) : null);
30+
}
31+
}

src/FormatDate.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Kiboko\Component\StringExpressionLanguage;
6+
7+
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
8+
9+
class FormatDate extends ExpressionFunction
10+
{
11+
public function __construct($name)
12+
{
13+
parent::__construct(
14+
$name,
15+
\Closure::fromCallable([$this, 'compile'])->bindTo($this),
16+
\Closure::fromCallable([$this, 'evaluate'])->bindTo($this)
17+
);
18+
}
19+
20+
private function compile(string $dateTime, string $format)
21+
{
22+
return <<<"PHP"
23+
{$dateTime}->format({$format})
24+
PHP;
25+
}
26+
27+
private function evaluate(array $context, string $dateTime, string $format)
28+
{
29+
return $dateTime->format($format);
30+
}
31+
}

src/StringExpressionLanguageProvider.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ public function getFunctions(): array
1414
ExpressionFunction::fromPhp('trim', 'trim'),
1515
ExpressionFunction::fromPhp('str_replace', 'replace'),
1616
new FileName('fileName'),
17+
new DateTime('dateTime'),
18+
new FormatDate('formatDate'),
1719
];
1820
}
1921
}

0 commit comments

Comments
 (0)