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

Get Url Contents Ez Twig Bundle Laravel Package

code-rhapsodie/get-url-contents-ez-twig-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Require the package via Composer:
    composer require code-rhapsodie/get-url-contents-ez-twig-bundle
    
  2. Enable the Bundle: Add to config/bundles.php:
    return [
        // ...
        CodeRhapsodie\GetUrlContentsEzTwigBundle\GetUrlContentsEzTwigBundle::class => ['all' => true],
    ];
    
  3. First Use Case: Fetch external content in Twig templates (e.g., embedding a remote RSS feed snippet or a public API response):
    {% set externalContent = get_url_contents('https://api.example.com/data') %}
    {{ externalContent|raw }}  {# Display raw HTML/JSON if needed #}
    

Implementation Patterns

Core Workflows

  1. Dynamic Content Injection

    • Use in Twig to fetch and render external resources (e.g., weather data, live stats) without server-side logic:
      {% if get_url_contents('https://status.example.com') contains 'operational' %}
          <div class="status-ok">All systems go!</div>
      {% endif %}
      
    • Caching: Combine with Twig’s {% cache %} to avoid repeated HTTP calls:
      {% cache for 3600 seconds %}
          {{ get_url_contents('https://slow-api.example.com') }}
      {% endcache %}
      
  2. Legacy eZ Publish Integration

    • Replace hardcoded external content in legacy templates with dynamic fetches:
      {def $content = get_url_contents($url)}{/def}
      {assign var="remoteData" value=$content}
      
    • Template Operators: Use in eZ Publish’s content.view.full.tpl for footer scripts or ads:
      {get_url_contents('https://ads.example.com/banner')|raw}
      
  3. API Proxying

    • Act as a lightweight proxy for internal services (e.g., fetching user-specific data from a microservice):
      {% set userData = get_url_contents('https://user-service.example.com/' ~ currentUser.id) %}
      

Integration Tips

  • Error Handling: Wrap calls in Twig’s {% if %} to handle failures gracefully:
    {% set content = get_url_contents('https://unreliable-api.example.com') %}
    {% if content == '' %}
        <p>Failed to load external content.</p>
    {% else %}
        {{ content|striptags }}
    {% endif %}
    
  • Security: Restrict allowed domains via a custom Twig extension (see Gotchas).
  • Performance: Use curl options (e.g., timeouts) via a custom service (extend the bundle’s UrlFetcher class).

Gotchas and Tips

Pitfalls

  1. No CORS/Authentication Support

    • The bundle uses raw curl without headers/cookies. For APIs requiring auth:
      {# ❌ Won't work #}
      {{ get_url_contents('https://api.example.com/protected', { 'headers': { 'Authorization': 'Bearer token' } }) }}
      
    • Workaround: Pre-fetch data in a controller and pass it to Twig via variables.
  2. Empty String on Failure

    • HTTP errors (4xx/5xx) or timeouts return ''. Use {% if %} checks or a custom filter to distinguish:
      {% set result = get_url_contents(url) %}
      {% if result == '' %}
          {# Handle error #}
      {% endif %}
      
  3. Legacy Template Quirks

    • eZ Publish’s template operator lacks Twig’s flexibility (e.g., no filters). Use Twig where possible.

Debugging

  • Check curl Errors: Enable debug mode in config/packages/dev.php to log HTTP failures:
    framework:
        twig:
            debug: true
    
  • Inspect Responses: Use a custom Twig filter to dump raw responses:
    {{ get_url_contents(url)|json_encode|raw }}  {# Debug JSON APIs #}
    

Extension Points

  1. Customize curl Options Override the bundle’s UrlFetcher service (defined in Resources/config/services.yaml):

    services:
        CodeRhapsodie\GetUrlContentsEzTwigBundle\Service\UrlFetcher:
            arguments:
                $timeout: 10  # Default: 30 seconds
                $allowedDomains: ['api.example.com', 'cdn.example.com']  # Whitelist
    
  2. Add Headers/Proxies Extend the UrlFetcher class to support headers:

    // src/Service/CustomUrlFetcher.php
    class CustomUrlFetcher extends UrlFetcher {
        public function fetch(string $url, array $options = []): string {
            $options['headers'] = $options['headers'] ?? [
                'User-Agent' => 'MyApp/1.0',
            ];
            return parent::fetch($url, $options);
        }
    }
    

    Update services.yaml to use your class.

  3. Twig Filter for Validation Create a filter to validate responses (e.g., check for JSON):

    // src/Twig/AppExtension.php
    class AppExtension extends \Twig\Extension\AbstractExtension {
        public function getFilters() {
            return [
                new \Twig\TwigFilter('is_valid_json', function($content) {
                    return json_decode($content) !== null;
                }),
            ];
        }
    }
    

    Usage:

    {% if get_url_contents(url)|is_valid_json %}
        {{ get_url_contents(url)|json_decode|json_encode|raw }}
    {% endif %}
    

Configuration Quirks

  • No Bundle Config: The bundle has no config/packages/ files, so all settings must be injected via services.
  • eZ Publish Compatibility: Test in legacy templates—some syntax (e.g., {assign}) may behave differently than Twig.

```markdown
## Maturity Considerations
- **Last Release (2020)**: Verify compatibility with your eZ Platform/Laravel version (if using eZ).
- **No Tests/Documentation**: Assume minimal edge-case handling; test thoroughly for production use.
- **MIT License**: Safe for commercial projects, but audit the `curl`-based implementation for your needs.
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
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
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