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

Static Site Bundle Laravel Package

braincrafted/static-site-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require cocur/build-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Cocur\BuildBundle\CocurBuildBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Define a build.yml in config/packages/cocur_build.yaml:

    cocur_build:
        output_dir: '%kernel.project_dir%/public/build'
        generators:
            file: ~
            directory: ~
            front_matter: ~
    
  3. First Use Case Create a controller to generate static content:

    // src/Controller/StaticPageController.php
    namespace App\Controller;
    
    use Cocur\BuildBundle\Generator\FrontMatterGenerator;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Response;
    
    class StaticPageController extends AbstractController
    {
        public function generateHomepage(FrontMatterGenerator $generator): Response
        {
            $content = $generator->generate(
                'homepage.md', // Source file (Markdown with front-matter)
                ['title' => 'Welcome'] // Front-matter data
            );
            file_put_contents($this->getParameter('cocur_build.output_dir').'/index.html', $content);
            return new Response('Generated!');
        }
    }
    

    Run the command to generate static files:

    php bin/console cocur:build
    

Implementation Patterns

Workflows

  1. Markdown + Front-Matter for Blog Posts

    • Use FrontMatterGenerator to parse Markdown files with metadata (e.g., posts/2023-10-01-intro.md).
    • Example front-matter:
      ---
      title: "Introduction"
      date: 2023-10-01
      tags: [getting-started]
      ---
      
    • Generate HTML in a loop:
      foreach (glob('src/Resources/posts/*.md') as $post) {
          $generator->generate($post, ['slug' => basename($post, '.md')]);
      }
      
  2. Dynamic JSON APIs as Static Files

    • Use JsonGenerator to cache API responses:
      $generator = $this->container->get('cocur_build.generator.json');
      $data = ['products' => $this->getProductsFromDB()];
      $generator->generate('products.json', $data);
      
  3. Directory Structure Mirroring

    • Use DirectoryGenerator to replicate a directory structure (e.g., for assets):
      cocur_build:
          generators:
              directory:
                  source: '%kernel.project_dir%/assets'
                  target: '%kernel.project_dir%/public/static'
      
  4. Twig Templates for Reusable Layouts

    • Combine with Twig to render dynamic content:
      $twig = $this->container->get('twig');
      $html = $twig->render('blog/post.html.twig', ['content' => $markdownContent]);
      file_put_contents($outputPath, $html);
      

Integration Tips

  • Symfony Events Trigger builds on kernel.terminate or custom events:

    // config/services.yaml
    services:
        App\EventListener\BuildListener:
            tags:
                - { name: kernel.event_listener, event: kernel.terminate, method: onTerminate }
    
    // src/EventListener/BuildListener.php
    class BuildListener {
        public function onTerminate(KernelEvents $event) {
            $this->container->get('cocur_build.builder')->build();
        }
    }
    
  • GitHub Actions CI Automate builds on push to main:

    # .github/workflows/build.yml
    jobs:
      build:
        runs-on: ubuntu-latest
        steps:
            - uses: actions/checkout@v3
            - run: composer install
            - run: php bin/console cocur:build
            - uses: peaceiris/actions-gh-pages@v3
              with:
                github_token: ${{ secrets.GITHUB_TOKEN }}
                publish_dir: ./public/build
    

Gotchas and Tips

Pitfalls

  1. Early Development Stage

    • The bundle is labeled as early development. Expect breaking changes between minor versions. Pin to a specific commit in composer.json if stability is critical:
      "cocur/build-bundle": "dev-master#123abc"
      
  2. Front-Matter Parsing Quirks

    • YAML front-matter must be valid. Test with yaml-lint.com.
    • Multi-line strings in front-matter may break. Use block scalars:
      ---
      description: |
          This is a
          multi-line
          string.
      ---
      
  3. File Overwrites

    • The build command overwrites files silently. Use --dry-run to preview changes:
      php bin/console cocur:build --dry-run
      
  4. Twig Integration Caveats

    • Twig templates must extend a base template if using layouts. Standalone templates render without context:
      {# ❌ Fails #}
      {% extends 'base.html.twig' %}
      
      {# ✅ Works #}
      {% block content %}{% endblock %}
      

Debugging

  1. Enable Debug Mode Set debug: true in config/packages/cocur_build.yaml to log generator output:

    cocur_build:
        debug: true
    
  2. Check Generator Output Inspect generated files in var/log/cocur_build.log or enable verbose mode:

    php bin/console cocur:build -v
    
  3. Common Errors

    • "Generator not found": Ensure the generator is registered in config/packages/cocur_build.yaml under generators.
    • "Source file not found": Verify paths are relative to the project root or use absolute paths with %kernel.project_dir%.

Extension Points

  1. Custom Generators Extend Cocur\BuildBundle\Generator\AbstractGenerator to create new formats (e.g., XmlGenerator):

    namespace App\Generator;
    
    use Cocur\BuildBundle\Generator\AbstractGenerator;
    
    class XmlGenerator extends AbstractGenerator {
        public function generate(string $source, array $data): string {
            // Custom logic
            return $this->renderXmlTemplate($data);
        }
    }
    

    Register in config/services.yaml:

    services:
        App\Generator\XmlGenerator:
            tags: ['cocur_build.generator']
    
  2. Pre/Post-Build Hooks Use Symfony’s compiler passes or event listeners to modify the build pipeline:

    // src/EventSubscriber/BuildSubscriber.php
    class BuildSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                'cocur_build.pre_build' => 'onPreBuild',
                'cocur_build.post_build' => 'onPostBuild',
            ];
        }
    
        public function onPreBuild(PreBuildEvent $event) {
            // Add files to build queue
            $event->addFile('src/Resources/extra.md');
        }
    }
    
  3. Override Default Config Use %kernel.project_dir%/config/packages/override/cocur_build.yaml to override settings without modifying the main config:

    cocur_build:
        output_dir: '%kernel.project_dir%/public/custom-build'
    
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.
besmartand-pro/php-quality-config
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views
spatie/ignition-contracts