Skip to content

feat: add wrapping of global function with existing check #175

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions ncs.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
declare(strict_types=1);

return [
// constant NULL, FALSE in src/PhpGenerator/Type.php
'constant_case' => false,
// constants in src/PhpGenerator/Type.php
'lowercase_static_reference' => false,
];
8 changes: 6 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ $function = new Nette\PhpGenerator\GlobalFunction('foo');
$function->setBody('return $a + $b;');
$function->addParameter('a');
$function->addParameter('b');
$function->wrapInExistingCheck();
echo $function;

// or use the PsrPrinter for output compliant with PSR-2 / PSR-12 / PER
Expand All @@ -306,9 +307,12 @@ echo $function;
The result is:

```php
function foo($a, $b)
if (! function_exists('foo'))
{
return $a + $b;
function foo($a, $b)
{
return $a + $b;
}
}
```

Expand Down
4 changes: 2 additions & 2 deletions src/PhpGenerator/Dumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@ private function dumpString(string $s): string

$utf8 = preg_match('##u', $s);
$escaped = preg_replace_callback(
$utf8 ? '#[\p{C}\\\\]#u' : '#[\x00-\x1F\x7F-\xFF\\\\]#',
$utf8 ? '#[\p{C}\\\]#u' : '#[\x00-\x1F\x7F-\xFF\\\]#',
fn($m) => $special[$m[0]] ?? (strlen($m[0]) === 1
? '\x' . str_pad(strtoupper(dechex(ord($m[0]))), 2, '0', STR_PAD_LEFT)
: '\u{' . strtoupper(ltrim(dechex(self::utf8Ord($m[0])), '0')) . '}'),
$s,
);
return $s === str_replace('\\\\', '\\', $escaped)
? "'" . preg_replace('#\'|\\\\(?=[\'\\\\]|$)#D', '\\\\$0', $s) . "'"
? "'" . preg_replace('#\'|\\\(?=[\'\\\]|$)#D', '\\\$0', $s) . "'"
: '"' . addcslashes($escaped, '"$') . '"';
}

Expand Down
14 changes: 14 additions & 0 deletions src/PhpGenerator/GlobalFunction.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ final class GlobalFunction
use Traits\CommentAware;
use Traits\AttributeAware;

private bool $wrapInExistingCheck = false;

public static function from(string|\Closure $function, bool $withBody = false): self
{
return (new Factory)->fromFunctionReflection(Nette\Utils\Callback::toReflection($function), $withBody);
Expand All @@ -38,4 +40,16 @@ public function __clone(): void
{
$this->parameters = array_map(fn($param) => clone $param, $this->parameters);
}


public function wrapInExistingCheck(bool $wrap = true): self
{
$this->wrapInExistingCheck = $wrap;
return $this;
}

public function getWrapInExistingCheck(): bool
{
return $this->wrapInExistingCheck;
}
}
4 changes: 2 additions & 2 deletions src/PhpGenerator/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public static function tagName(string $name, string $of = PhpNamespace::NameNorm

public static function simplifyTaggedNames(string $code, ?PhpNamespace $namespace): string
{
return preg_replace_callback('~/\*\(([ncf])\*/([\w\x7f-\xff\\\\]++)~', function ($m) use ($namespace) {
return preg_replace_callback('~/\*\(([ncf])\*/([\w\x7f-\xff\\\]++)~', function ($m) use ($namespace) {
[, $of, $name] = $m;
return $namespace
? $namespace->simplifyType($name, $of)
Expand Down Expand Up @@ -106,7 +106,7 @@ public static function isIdentifier(mixed $value): bool

public static function isNamespaceIdentifier(mixed $value, bool $allowLeadingSlash = false): bool
{
$re = '#^' . ($allowLeadingSlash ? '\\\\?' : '') . self::ReIdentifier . '(\\\\' . self::ReIdentifier . ')*$#D';
$re = '#^' . ($allowLeadingSlash ? '\\\?' : '') . self::ReIdentifier . '(\\\\' . self::ReIdentifier . ')*$#D';
return is_string($value) && preg_match($re, $value);
}

Expand Down
2 changes: 1 addition & 1 deletion src/PhpGenerator/PhpNamespace.php
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ public function resolveName(string $name, string $of = self::NameNormal): string
*/
public function simplifyType(string $type, string $of = self::NameNormal): string
{
return preg_replace_callback('~[\w\x7f-\xff\\\\]+~', fn($m) => $this->simplifyName($m[0], $of), $type);
return preg_replace_callback('~[\w\x7f-\xff\\\]+~', fn($m) => $this->simplifyName($m[0], $of), $type);
}


Expand Down
6 changes: 5 additions & 1 deletion src/PhpGenerator/Printer.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,17 @@ public function printFunction(GlobalFunction $function, ?PhpNamespace $namespace
$body = $this->printFunctionBody($function);
$braceOnNextLine = $this->isBraceOnNextLine(str_contains($params, "\n"), (bool) $returnType);

return $this->printDocComment($function)
$functionPrint = $this->printDocComment($function)
. $this->printAttributes($function->getAttributes())
. $line
. $params
. $returnType
. ($braceOnNextLine ? "\n" : ' ')
. "{\n" . $this->indent($body) . "}\n";

$wrapper = "if (! function_exists('{$function->getName()}'))\n{\n{$this->indent($functionPrint)}}\n";

return $function->getWrapInExistingCheck() ? $wrapper : $functionPrint;
}


Expand Down
4 changes: 2 additions & 2 deletions tests/PhpGenerator/Dumper.dump().phpt
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ Assert::same("'Hello'", $dumper->dump('Hello'));
Assert::same('"\t\n\r\e"', $dumper->dump("\t\n\r\e"));
Assert::same('"\u{FEFF}"', $dumper->dump("\xEF\xBB\xBF")); // BOM
Assert::same('\'$"\\\\\'', $dumper->dump('$"\\'));
Assert::same('\'$"\\ \x00\'', $dumper->dump('$"\\ \x00')); // no escape
Assert::same('"\\$\\"\\\\ \x00"', $dumper->dump("$\"\\ \x00"));
Assert::same('\'$"\ \x00\'', $dumper->dump('$"\ \x00')); // no escape
Assert::same('"\$\"\\\ \x00"', $dumper->dump("$\"\\ \x00"));
Assert::same(
"'I\u{F1}t\u{EB}rn\u{E2}ti\u{F4}n\u{E0}liz\u{E6}ti\u{F8}n'",
$dumper->dump("I\u{F1}t\u{EB}rn\u{E2}ti\u{F4}n\u{E0}liz\u{E6}ti\u{F8}n"), // Iñtërnâtiônàlizætiøn
Expand Down
32 changes: 32 additions & 0 deletions tests/PhpGenerator/GlobalFunction.wrapped.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

use Nette\PhpGenerator\GlobalFunction;

require __DIR__ . '/../bootstrap.php';


$function = new GlobalFunction('test');
$function->setBody('return $a + $b;');
$function->addAttribute('ExampleAttribute');
$function->addComment('My Function');
$function->wrapInExistingCheck();

same(
<<<'XX'
if (! function_exists('test'))
{
/**
* My Function
*/
#[ExampleAttribute]
function test()
{
return $a + $b;
}
}

XX,
(string) $function,
);
6 changes: 3 additions & 3 deletions tests/PhpGenerator/Helpers.isNamespaceIdentifier.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ Assert::true(Helpers::isNamespaceIdentifier("\x7F"));
Assert::true(Helpers::isNamespaceIdentifier("\x7F\\\x7F"));
Assert::false(Helpers::isNamespaceIdentifier('0Item'));
Assert::true(Helpers::isNamespaceIdentifier('Item\Item'));
Assert::false(Helpers::isNamespaceIdentifier('Item\\\\Item'));
Assert::false(Helpers::isNamespaceIdentifier('\\Item'));
Assert::false(Helpers::isNamespaceIdentifier('Item\\\Item'));
Assert::false(Helpers::isNamespaceIdentifier('\Item'));
Assert::false(Helpers::isNamespaceIdentifier('Item\\'));

Assert::true(Helpers::isNamespaceIdentifier('\\Item', allowLeadingSlash: true));
Assert::true(Helpers::isNamespaceIdentifier('\Item', allowLeadingSlash: true));
Assert::false(Helpers::isNamespaceIdentifier('Item\\', allowLeadingSlash: true));
4 changes: 2 additions & 2 deletions tests/PhpGenerator/PhpFile.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ $interfaceF
$traitG = $file->addTrait('Baz\G');
Assert::same($file->addNamespace('Baz'), $traitG->getNamespace());

$file->addFunction('Baz\\f2')
$file->addFunction('Baz\f2')
->setReturnType('Foo\B');


Expand Down Expand Up @@ -112,7 +112,7 @@ Assert::same([
'FooBar\I',
], array_keys($file->getClasses()));

Assert::same(['Baz\\f2', 'f1'], array_keys($file->getFunctions()));
Assert::same(['Baz\f2', 'f1'], array_keys($file->getFunctions()));



Expand Down