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: $useStr = strlen($tmp = implode(', ', $uses)) > Helpers::WRAP_LENGTH && count($uses) > 1
46: ? "\n\t" . implode(",\n\t", $uses) . "\n"
47: : $tmp;
48:
49: return 'function '
50: . ($this->returnReference ? '&' : '')
51: . $this->parametersToString()
52: . ($this->uses ? " use ($useStr)" : '')
53: . $this->returnTypeToString()
54: . " {\n" . Nette\Utils\Strings::indent(ltrim(rtrim($this->body) . "\n"), 1) . '}';
55: }
56:
57:
58: /**
59: * @param Parameter[]
60: * @return static
61: */
62: public function setUses(array $uses)
63: {
64: foreach ($uses as $use) {
65: if (!$use instanceof Parameter) {
66: throw new Nette\InvalidArgumentException('Argument must be Nette\PhpGenerator\Parameter[].');
67: }
68: }
69: $this->uses = $uses;
70: return $this;
71: }
72:
73:
74: /**
75: * @return array
76: */
77: public function getUses()
78: {
79: return $this->uses;
80: }
81:
82:
83: /**
84: * @return Parameter
85: */
86: public function addUse($name)
87: {
88: return $this->uses[] = new Parameter($name);
89: }
90: }
91: