1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6: */
7:
8: namespace Nette\PhpGenerator;
9:
10: use Nette;
11:
12:
13: /**
14: * Closure.
15: *
16: * @property string $body
17: */
18: class Closure
19: {
20: use Nette\SmartObject;
21: use Traits\FunctionLike;
22:
23: /** @var Parameter[] */
24: private $uses = [];
25:
26:
27: /**
28: * @return static
29: */
30: public static function from(\Closure $closure)
31: {
32: return (new Factory)->fromFunctionReflection(new \ReflectionFunction($closure));
33: }
34:
35:
36: /**
37: * @return string PHP code
38: */
39: public function __toString()
40: {
41: $uses = [];
42: foreach ($this->uses as $param) {
43: $uses[] = ($param->isReference() ? '&' : '') . '$' . $param->getName();
44: }
45: return 'function '
46: . ($this->returnReference ? '&' : '')
47: . $this->parametersToString()
48: . ($this->uses ? ' use (' . implode(', ', $uses) . ')' : '')
49: . $this->returnTypeToString()
50: . " {\n" . Nette\Utils\Strings::indent(ltrim(rtrim($this->body) . "\n"), 1) . '}';
51: }
52:
53:
54: /**
55: * @param Parameter[]
56: * @return static
57: */
58: public function setUses(array $uses)
59: {
60: foreach ($uses as $use) {
61: if (!$use instanceof Parameter) {
62: throw new Nette\InvalidArgumentException('Argument must be Nette\PhpGenerator\Parameter[].');
63: }
64: }
65: $this->uses = $uses;
66: return $this;
67: }
68:
69:
70: /**
71: * @return array
72: */
73: public function getUses()
74: {
75: return $this->uses;
76: }
77:
78:
79: /**
80: * @return Parameter
81: */
82: public function addUse($name)
83: {
84: return $this->uses[] = new Parameter($name);
85: }
86: }
87: