Skip to content

Commit

Permalink
Merge branch '1.x' of https://github.com/binafy/laravel-stub into add…
Browse files Browse the repository at this point in the history
…-generateForce-method
  • Loading branch information
milwad-dev committed Nov 22, 2024
2 parents 495de15 + 230137c commit a430daa
Show file tree
Hide file tree
Showing 6 changed files with 167 additions and 4 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ composer.lock
.phpunit.result.cache
.phpunit.xml
coverage
tests/App/new-test.php
tests/App/*.php
tests/Feature/test.stub
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
- [`replace`](#replace)
- [`replaces`](#replaces)
- [`moveStub`](#move-stub)
- [`conditions`](#conditions)
- [`download`](#download)
- [`generate`](#generate)
- [`generateForce`](#generate-force)
Expand Down Expand Up @@ -183,6 +184,49 @@ LaravelStub::from(__DIR__ . 'model.stub')

After running this code, the `model.stub` didn't exist.

<a name="conditions"></a>
### `conditions`

The `conditions` method allows you to define conditional blocks within your stub files.
You can specify conditions that determine whether certain parts of the stub should be included or excluded based on provided values or closures.

```php
<?php
LaravelStub::from(__DIR__ . 'model.stub')
->to(__DIR__ . '/App')
->name('new-model')
->ext('php')
->replaces([
'NAMESPACE' => 'App',
'CLASS' => 'Milwad'
])
->conditions([
'hasController' => true,
'hasController' => fn() => return false, // or with closure
])
->generate();
```

> NOTE: Ensure that your stub files contain the appropriate conditional placeholders (e.g., {{ if isEnabled }}) to utilize this method effectively.
Your stub code should looks like this:

```php
<?php

namespace {{ NAMESPACE }};

class {{ CLASS }}
{
{{ if hasController }}
public function controller()
{
// Controller logic here
}
{{ endif }}
}
```

<a name="download"></a>
### `download`

Expand Down
1 change: 1 addition & 0 deletions src/Facades/LaravelStub.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* @method static static replaces(array $replaces)
* @method static mixed download()
* @method static bool generate()
* @method static static conditions(array<string, bool|mixed|Closure> $conditions)
*
* @see \Binafy\LaravelStub\LaravelStub
*/
Expand Down
45 changes: 44 additions & 1 deletion src/LaravelStub.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Binafy\LaravelStub;

use Closure;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Response;
use RuntimeException;
Expand Down Expand Up @@ -50,6 +51,13 @@ class LaravelStub
*/
protected bool $moveStub = false;

/**
* The list of conditions.
*
* @var array
*/
protected array $conditions = [];

/**
* Set stub path.
*/
Expand Down Expand Up @@ -122,6 +130,19 @@ public function moveStub(): static
return $this;
}

/**
* Set conditions.
*
* @param array<string, bool|mixed|Closure> $conditions
* @return static
*/
public function conditions(array $conditions): static
{
$this->conditions = $conditions;

return $this;
}

/**
* Download the stub file.
*/
Expand All @@ -147,7 +168,7 @@ public function generate(bool $force = false): bool
{
// Check path is valid
if (! File::exists($this->from)) {
throw new RuntimeException('The stub file does not exist, please enter a valid path.');
throw new RuntimeException("The {$this->from} stub file does not exist, please enter a valid path.");
}

// Check destination path is valid
Expand All @@ -168,6 +189,28 @@ public function generate(bool $force = false): bool
$content = str_replace("{{ $search }}", $value, $content);
}

// Process conditions
foreach ($this->conditions as $condition => $value) {
if ($value instanceof Closure) {
$value = $value();
}

if ($value) {
// Remove condition placeholders along with any leading whitespace and newlines
$content = preg_replace("/^[ \t]*{{ if $condition }}\s*\n|^[ \t]*{{ endif }}\s*\n/m", '', $content);
continue;
}

// Remove the entire block including any leading whitespace and newlines
$content = preg_replace("/^[ \t]*{{ if $condition }}\s*\n.*?^[ \t]*{{ endif }}\s*\n/ms", '', $content);
}

// Remove any remaining conditional tags and their lines
$content = preg_replace("/^[ \t]*{{ if .*? }}\s*\n|^[ \t]*{{ endif .*? }}\s*\n/m", '', $content);

// Remove any remaining empty lines
$content = preg_replace("/^[ \t]*\n/m", '', $content);

// Get correct path
$path = $this->getPath();

Expand Down
58 changes: 56 additions & 2 deletions tests/Feature/LaravelStubTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

use Binafy\LaravelStub\Facades\LaravelStub;
use Illuminate\Support\Facades\File;

use function PHPUnit\Framework\assertFileDoesNotExist;
use function PHPUnit\Framework\assertFileExists;
Expand Down Expand Up @@ -54,7 +55,7 @@

assertFileDoesNotExist(__DIR__ . '/../App/new-test.php');
assertFileExists(__DIR__ . '/../App/test.stub');
})->expectExceptionMessage('The stub file does not exist, please enter a valid path.');
})->expectExceptionMessage('The test.stub stub file does not exist, please enter a valid path.');

test('throw exception when destination path is invalid', function () {
LaravelStub::from(__DIR__ . '/test.stub')
Expand Down Expand Up @@ -101,6 +102,59 @@
assertFileDoesNotExist(__DIR__ . '/../App/test.stub');
});

test('generate stub successfully when all conditions are met', function () {
$stub = __DIR__ . '/test.stub';

$testCondition = true;

$generate = LaravelStub::from($stub)
->to(__DIR__ . '/../App')
->conditions([
'CONDITION_ONE' => true,
'CONDITION_TWO' => $testCondition,
'CONDITION_THREE' => fn() => true,
])
->name('conditional-test')
->ext('php')
->generate();

assertTrue($generate);
assertFileExists(__DIR__ . '/../App/conditional-test.php');

$content = File::get(__DIR__ . '/../App/conditional-test.php');
expect($content)->toContain('public function handle(): void');
expect($content)->toContain('public function users(): void');
expect($content)->toContain('public function roles(): void');
});

test('generate stub successfully when conditions are not met', function () {
$stub = __DIR__ . '/test.stub';

$testCondition = false;

$generate = LaravelStub::from($stub)
->to(__DIR__ . '/../App')
->conditions([
'CONDITION_ONE' => false,
'CONDITION_TWO' => $testCondition,
'CONDITION_THREE' => fn() => false,
])
->name('conditional-test-false')
->ext('php')
->generate();

assertTrue($generate);
assertFileExists(__DIR__ . '/../App/conditional-test-false.php');

$content = File::get(__DIR__ . '/../App/conditional-test-false.php');
expect($content)
->not->toContain('public function handle(): void')
->and($content)
->not->toContain('public function users(): void')
->and($content)
->not->toContain('public function roles(): void');
});

test('generate stub successfully when force is true', function () {
$stub = __DIR__ . '/test.stub';

Expand All @@ -126,7 +180,7 @@
->name('new-test')
->ext('php')
->moveStub()
->generate();
->generateForce();

expect(file_get_contents(__DIR__ . '/../App/new-test.php'))
->toContain('Binafy')
Expand Down
21 changes: 21 additions & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,27 @@ public function createStubFile(): void
class {{ CLASS }}
{
use Illuminate\Database\Eloquent\Factories\{{ TRAIT }};
{{ if CONDITION_ONE }}
public function handle(): void
{
//
}
{{ endif }}
{{ if CONDITION_TWO }}
public function users(): void
{
//
}
{{ endif }}
{{ if CONDITION_THREE }}
public function roles(): void
{
//
}
{{ endif }}
}
EOL
);
Expand Down

0 comments on commit a430daa

Please sign in to comment.