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

Polr Api Bundle Laravel Package

adeelnawaz/polr-api-bundle

Symfony 4/5 bundle wrapping adeelnawaz/polr-api-client to integrate the Polr URL shortener REST API. Provides a PolrApiService for calling endpoints with DTOs, supports API quota throttling, and throws ApiResponseException on failures.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Bundle Run:

    composer require adeelnawaz/polr-api-bundle
    
  2. Configure the Bundle Create config/packages/polr_api.yml (Symfony 5+) or config/polr_api.yml (Symfony 4):

    polr_api:
      api_url: '%env(POLR_API_URL)%'
      api_key: '%env(POLR_API_KEY)%'
      api_quota: '%env(int:POLR_API_QUOTA)%'
    

    Add .env variables:

    POLR_API_URL=https://your-polr-instance.com/api
    POLR_API_KEY=your_api_key_here
    POLR_API_QUOTA=100  # Adjust based on Polr's rate limits
    
  3. First API Call Inject PolrApiService into a controller or service and use it:

    use AdeelNawaz\PolrApiBundle\Service\PolrApiService;
    
    class MyController extends AbstractController
    {
        public function __construct(private PolrApiService $polrApi)
        {
        }
    
        public function index()
        {
            $links = $this->polrApi->getLinks();
            return $this->json($links);
        }
    }
    

Where to Look First

  • Service Documentation: The PolrApiService mirrors the underlying polr-api-client methods (e.g., getLinks(), createLink(), deleteLink()).
  • Polr API Docs: Refer to Polr’s official API docs for available endpoints and payload structures.
  • Bundle Tests: Check the bundle’s tests for usage examples.

Implementation Patterns

Common Workflows

1. Link Management

  • Fetch Links:
    $links = $this->polrApi->getLinks(['per_page' => 10]);
    
  • Create a Link:
    $newLink = $this->polrApi->createLink([
        'title' => 'My Shortened Link',
        'url' => 'https://example.com/long-url',
    ]);
    
  • Delete a Link:
    $this->polrApi->deleteLink($linkId);
    

2. Rate Limit Handling

  • Configure api_quota in polr_api.yml to respect Polr’s rate limits (e.g., api_quota: 60 for 60 calls/minute).
  • The bundle automatically delays requests if the quota is exceeded. Monitor logs for PolrApiException with quota-related messages.

3. Error Handling

  • Wrap API calls in a try-catch to handle exceptions:
    try {
        $link = $this->polrApi->getLink($id);
    } catch (\AdeelNawaz\PolrApiBundle\Exception\PolrApiException $e) {
        $this->addFlash('error', $e->getMessage());
        return $this->redirectToRoute('home');
    }
    

4. Dependency Injection

  • Controllers: Inject PolrApiService directly (as shown above).
  • Services: Extend functionality by creating a custom service:
    class LinkManager
    {
        public function __construct(private PolrApiService $polrApi) {}
    
        public function shortenUrl(string $url, string $title): array
        {
            return $this->polrApi->createLink(compact('url', 'title'));
        }
    }
    

5. Configuration Overrides

  • Override default config in config/packages/polr_api.yml:
    polr_api:
        api_url: '%env(POLR_CUSTOM_URL)%'  # Override per environment
        api_quota: 30
    

6. Testing

  • Mock PolrApiService in PHPUnit:
    $this->createMock(PolrApiService::class)
         ->method('getLinks')
         ->willReturn([['id' => 1, 'title' => 'Test']]);
    

Integration Tips

  1. Symfony Forms Use the bundle to validate or fetch data for forms:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('url', TextType::class, [
            'constraints' => [
                new Callback([$this->polrApi, 'validateUrl']),
            ],
        ]);
    }
    
  2. Event Listeners Trigger actions after link creation/deletion:

    public function onLinkCreated(LinkEvent $event)
    {
        $this->polrApi->updateLink($event->getLinkId(), ['notes' => 'Auto-generated']);
    }
    
  3. Command-Line Tools Create a Symfony command to manage links:

    class PolrLinkCommand extends Command
    {
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $links = $this->polrApi->getLinks();
            foreach ($links as $link) {
                $output->writeln($link['title'] . ': ' . $link['url']);
            }
        }
    }
    
  4. Caching Responses Cache frequent API calls (e.g., fetching all links):

    $links = $this->cache->get('polr_links', function () {
        return $this->polrApi->getLinks();
    }, 300); // Cache for 5 minutes
    

Gotchas and Tips

Pitfalls

  1. Quota Mismatch

    • If api_quota is set lower than Polr’s actual limit, you’ll hit artificial delays or errors. Set it to 0 for no delay (unlimited) or match Polr’s documented rate limit (e.g., 60 for 60 calls/minute).
  2. API Key Permissions

    • Ensure your Polr API key has the required permissions (e.g., read:links, write:links). Invalid keys throw PolrApiException with HTTP 403/401.
  3. Endpoint Changes

    • The bundle wraps polr-api-client, which may lag behind Polr’s API updates. Check the Polr API changelog and update the underlying package if needed:
      composer require adeelnawaz/polr-api-client:dev-main
      
  4. Symfony Version Conflicts

    • The bundle is not compatible with Symfony 3. Use v0.1.1 for Symfony 3 projects.
  5. Environment Variables

    • Forgetting to set POLR_API_URL or POLR_API_KEY in .env will throw a RuntimeException during service compilation. Validate with:
      php bin/console debug:container | grep polr
      

Debugging

  1. Enable Debug Mode Set POLR_API_DEBUG=true in .env to log raw API responses:

    polr_api:
      debug: '%env(bool:POLR_API_DEBUG)%'
    
  2. Check HTTP Status Codes Exceptions include the HTTP status code. Example:

    catch (PolrApiException $e) {
        if ($e->getCode() === 404) {
            // Handle "Link not found"
        }
    }
    
  3. Network Issues

    • If requests hang, verify:
      • Polr’s API URL is correct (e.g., https://your-polr-instance.com/api).
      • No firewall/proxy blocks outbound requests to Polr.

Tips

  1. Extend the Service Create a decorator to add custom logic:

    class CustomPolrApiService extends PolrApiService
    {
        public function getLinksWithStats()
        {
            $links = parent::getLinks();
            return array_map(function ($link) {
                $link['stats'] = $this->fetchLinkStats($link['id']);
                return $link;
            }, $links);
        }
    }
    

    Register it in services.yaml:

    services:
        AdeelNawaz\PolrApiBundle\Service\PolrApiService:
            class: App\Service\CustomPolrApiService
    
  2. Use DTOs for Responses Map API responses to PHP objects for type safety:

    class LinkDto
    {
        public function __construct(
            public string $id,
            public string $title,
            public string $url,
        ) {}
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
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