blob: 494d45b08c53cd74b75829d1eb291e6f62dd7dd4 [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) Fabien Potencier
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Twig;
13
14use Twig\Node\Expression\FunctionExpression;
15use Twig\Node\Node;
16
17/**
18 * Represents a template function.
19 *
20 * @author Fabien Potencier <fabien@symfony.com>
21 *
22 * @see https://twig.symfony.com/doc/templates.html#functions
23 */
24final class TwigFunction
25{
26 private $name;
27 private $callable;
28 private $options;
29 private $arguments = [];
30
31 /**
32 * @param callable|null $callable A callable implementing the function. If null, you need to overwrite the "node_class" option to customize compilation.
33 */
34 public function __construct(string $name, $callable = null, array $options = [])
35 {
36 $this->name = $name;
37 $this->callable = $callable;
38 $this->options = array_merge([
39 'needs_environment' => false,
40 'needs_context' => false,
41 'is_variadic' => false,
42 'is_safe' => null,
43 'is_safe_callback' => null,
44 'node_class' => FunctionExpression::class,
45 'deprecated' => false,
46 'alternative' => null,
47 ], $options);
48 }
49
50 public function getName(): string
51 {
52 return $this->name;
53 }
54
55 /**
56 * Returns the callable to execute for this function.
57 *
58 * @return callable|null
59 */
60 public function getCallable()
61 {
62 return $this->callable;
63 }
64
65 public function getNodeClass(): string
66 {
67 return $this->options['node_class'];
68 }
69
70 public function setArguments(array $arguments): void
71 {
72 $this->arguments = $arguments;
73 }
74
75 public function getArguments(): array
76 {
77 return $this->arguments;
78 }
79
80 public function needsEnvironment(): bool
81 {
82 return $this->options['needs_environment'];
83 }
84
85 public function needsContext(): bool
86 {
87 return $this->options['needs_context'];
88 }
89
90 public function getSafe(Node $functionArgs): ?array
91 {
92 if (null !== $this->options['is_safe']) {
93 return $this->options['is_safe'];
94 }
95
96 if (null !== $this->options['is_safe_callback']) {
97 return $this->options['is_safe_callback']($functionArgs);
98 }
99
100 return [];
101 }
102
103 public function isVariadic(): bool
104 {
105 return (bool) $this->options['is_variadic'];
106 }
107
108 public function isDeprecated(): bool
109 {
110 return (bool) $this->options['deprecated'];
111 }
112
113 public function getDeprecatedVersion(): string
114 {
115 return \is_bool($this->options['deprecated']) ? '' : $this->options['deprecated'];
116 }
117
118 public function getAlternative(): ?string
119 {
120 return $this->options['alternative'];
121 }
122}