Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phar Builder Bundle Laravel Package

efrane/phar-builder-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the Bundle**:
   ```bash
   composer require efrane/phar-builder-bundle

Register in config/bundles.php:

EFrane\PharBuilder\Bundle\PharBuilderBundle::class => ['all' => true],
  1. First Use Case: CLI Command for PHAR Creation Create a custom command extending EFrane\PharBuilder\Command\AbstractPharCommand:

    use EFrane\PharBuilder\Command\AbstractPharCommand;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    namespace App\Command;
    
    class BuildAppPhar extends AbstractPharCommand
    {
        protected function configure(): void
        {
            $this->setName('app:build-phar');
        }
    
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $this->buildPhar(
                'app.phar',
                ['src/', 'vendor/autoload.php'],
                ['--web-root', 'public']
            );
            return Command::SUCCESS;
        }
    }
    

    Run with:

    php bin/console app:build-phar
    
  2. Key Configuration Check config/packages/phar_builder.yaml for default settings (e.g., stub templates, excluded files).


Implementation Patterns

Common Workflows

  1. Dynamic File Inclusion Use addFiles() with glob patterns or arrays:

    $this->buildPhar('app.phar', [
        'src/**/*.php',
        'config/packages/*.yaml',
        'public/assets/**/*'
    ]);
    
  2. Stub Customization Override the default PHAR stub by:

    • Placing a stub.txt in config/packages/phar_builder/ or
    • Passing a custom stub path:
      $this->buildPhar('app.phar', [], [], 'custom-stub.txt');
      
  3. Dependency Management Exclude unnecessary files (e.g., tests, dev dependencies):

    $this->buildPhar('app.phar', ['src/', 'vendor/'], [
        '--exclude' => 'tests/*',
        '--exclude' => 'vendor/*/Tests/*'
    ]);
    
  4. Web Root Handling For web-accessible PHARs, specify the web root:

    $this->buildPhar('app.phar', ['src/', 'public/'], [
        '--web-root', 'public'
    ]);
    
  5. Post-Build Hooks Extend AbstractPharCommand to run scripts after PHAR creation:

    protected function postBuild(string $pharPath): void
    {
        $this->getOutput()->writeln(sprintf('PHAR created at %s', $pharPath));
        // Example: Sign the PHAR or upload it
    }
    
  6. Environment-Specific Builds Use Symfony’s environment-aware services to conditionally include files:

    $files = $this->getParameter('kernel.environment') === 'prod'
        ? ['src/', 'public/prod-assets/']
        : ['src/', 'public/dev-assets/'];
    

Integration Tips

  • Composer Scripts: Trigger PHAR builds via composer.json:
    {
        "scripts": {
            "build-phar": "php bin/console app:build-phar"
        }
    }
    
  • CI/CD Pipelines: Use the bundle in GitHub Actions or GitLab CI:
    - run: php bin/console app:build-phar
    
  • Symfony Flex Recipes: Create a custom recipe to auto-configure the bundle for new projects.

Gotchas and Tips

Pitfalls

  1. Alpha Stage Limitations

    • Avoid production use; expect breaking changes.
    • Test thoroughly in staging before any non-dev adoption.
  2. PHAR Security Risks

    • Stub Validation: Always validate the stub template to prevent malicious code injection.
      // Example: Sanitize stub content
      $stub = file_get_contents('stub.txt');
      if (strpos($stub, 'eval(') !== false) {
          throw new \RuntimeException('Stub contains unsafe eval() call.');
      }
      
    • File Exclusions: Ensure sensitive files (e.g., .env, composer.lock) are excluded:
      $this->buildPhar('app.phar', [], [
          '--exclude' => '.env',
          '--exclude' => 'composer.lock'
      ]);
      
  3. Dependency Conflicts

    • The bundle relies on phar.io/phar and symfony/console. Conflicts may arise with other PHAR-related packages.
    • Resolve with Composer’s replace or conflict directives.
  4. Web Root Misconfiguration

    • Incorrect --web-root flags can break PHAR execution. Verify the path is relative to the PHAR’s root.
  5. File Permissions

    • PHAR files require executable permissions on Unix-like systems:
      chmod +x app.phar
      

Debugging

  • Verbose Output: Enable debug mode in the command:
    $this->setDebug(true);
    
  • Dry Runs: Simulate builds without writing files:
    $this->buildPhar('app.phar', [], ['--dry-run']);
    
  • Logging: Use Symfony’s logger to track build steps:
    $this->logger->info('Building PHAR with files:', ['files' => $files]);
    

Extension Points

  1. Custom Builders Extend EFrane\PharBuilder\Builder\BuilderInterface for specialized logic (e.g., signing, compression):

    namespace App\Builder;
    
    use EFrane\PharBuilder\Builder\BuilderInterface;
    
    class CustomBuilder implements BuilderInterface
    {
        public function build(string $pharPath, array $files, array $options): void
        {
            // Custom logic (e.g., add a signature)
        }
    }
    

    Register as a service and pass to buildPhar() via options:

    $this->buildPhar('app.phar', [], [], [], new CustomBuilder());
    
  2. Stub Templates Override the default stub by:

    • Placing a stub.txt in config/packages/phar_builder/ or
    • Using a service to dynamically generate stubs:
      # config/services.yaml
      services:
          App\Stub\DynamicStubGenerator:
              arguments:
                  $environment: '%kernel.environment%'
      
  3. Pre/Post-Build Events Subscribe to Symfony events (e.g., console.command) to hook into the build lifecycle:

    use Symfony\Component\Console\Event\ConsoleCommandEvent;
    
    $eventDispatcher->addListener(ConsoleCommandEvent::class, function (ConsoleCommandEvent $event) {
        if ($event->getCommand()->getName() === 'app:build-phar') {
            // Pre-build logic
        }
    });
    

Configuration Quirks

  • Default Stub Path: The bundle looks for stub.txt in:
    1. config/packages/phar_builder/
    2. The bundle’s Resources/stubs/ directory (fallback).
  • Option Parsing: CLI options (e.g., --web-root) are passed directly to phar.io/phar. Refer to its docs for supported flags.
  • Environment Variables: Use Symfony’s parameter bag for dynamic paths:
    $this->buildPhar(
        $this->getParameter('phar.output_dir').'/app.phar',
        [$this->getParameter('kernel.project_dir').'/src/']
    );
    

```markdown
### Pro Tips
1. **PHAR Signing**: Integrate with `webmozart/php-signature` to sign PHARs post-build:
   ```php
   use Webmozart\PhpSignature\Signature;

   protected function postBuild(string $pharPath): void
   {
       $signature = new Signature();
       $signature->signFile($pharPath, 'private.key');
   }
  1. Versioned PHARs: Append Git hashes or timestamps to filenames:

    $pharName = sprintf('app-%s.phar', exec('git rev-parse --short HEAD'));
    $this->buildPhar($pharName, ['src/']);
    
  2. Dependency Optimization: Use phar.io/phar's --exclude to strip dev dependencies:

    $this->buildPhar('app.phar', [], [
        '--exclude' => 'vendor/*/Tests/*',
        '--exclude' => 'vendor/*/Resources/*'
    ]);
    
  3. Cross-Platform Paths: Normalize paths for Windows/Linux compatibility:

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment