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

Net Url2 Laravel Package

pear/net_url2

PEAR Net_URL2 is a small PHP utility for parsing, validating, and manipulating URLs. It builds and edits URL components, handles query strings, resolves relative URLs, and offers easy getters/setters for scheme, host, path, port, user info, and fragments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require pear/net_url2
    

    Add to composer.json if not using autoloading globally:

    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case Parse a URL into components:

    use Net_URL2;
    
    $url = new Net_URL2('https://example.com/path/to/resource?query=value#fragment');
    $parsed = $url->getParts();
    // Returns associative array: ['scheme', 'host', 'path', 'query', 'fragment', ...]
    
  3. Where to Look First

    • PEAR Documentation (if available).
    • Source code: Net/URL2.php (check for methods like getParts(), setParts(), get(), set()).
    • Test cases in the package for edge cases (e.g., malformed URLs).

Implementation Patterns

Core Workflows

  1. Parsing and Reconstructing URLs

    $url = new Net_URL2('https://user:[email protected]:8080/path?query=1#frag');
    $parts = $url->getParts(); // Extract components
    $reconstructed = $url->get(); // Rebuild URL string
    
  2. Handling Relative URLs Resolve relative paths against a base URL:

    $base = new Net_URL2('https://example.com/base/');
    $relative = new Net_URL2('subpath');
    $absolute = $base->resolve($relative); // 'https://example.com/base/subpath'
    
  3. Query String Manipulation Parse/modify query parameters:

    $url = new Net_URL2('https://example.com?foo=bar&baz=qux');
    $query = $url->getQuery(); // ['foo' => 'bar', 'baz' => 'qux']
    $url->setQuery(['foo' => 'updated']); // Updates query string
    
  4. Validation and Sanitization Check URL validity or enforce schemes/hosts:

    if ($url->isValid()) {
        // Proceed
    }
    $url->setScheme('https'); // Enforce HTTPS
    

Integration Tips

  • Laravel Request Handling Parse incoming requests:
    $requestUrl = new Net_URL2(request()->getRequestUri());
    $queryParams = $requestUrl->getQuery();
    
  • API Response URLs Generate canonical URLs for responses:
    $apiUrl = new Net_URL2('https://api.example.com/v1');
    $resourceUrl = $apiUrl->resolve('/users/123');
    return response()->json(['url' => $resourceUrl->get()]);
    
  • Middleware for URL Normalization Normalize URLs in middleware (e.g., enforce trailing slashes):
    $url = new Net_URL2($request->url());
    if (!$url->getPath() || substr($url->getPath(), -1) !== '/') {
        return redirect($url->setPath($url->getPath() . '/')->get());
    }
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity in Schemes/Hosts

    • Schemes (e.g., HTTP vs http) and hosts may be case-sensitive in parsing. Use strtolower() if consistency is critical:
      $url->setScheme(strtolower($url->getScheme()));
      
  2. Query String Encoding

    • The package may not handle URL-encoding/decoding of query values automatically. Manually encode/decode:
      $encoded = urlencode($value); // Before setting query
      $decoded = urldecode($query['param']); // After getting query
      
  3. Fragment Handling

    • Fragments (#fragment) are parsed but may not be preserved in all operations. Test edge cases:
      $url = new Net_URL2('https://example.com#test');
      $url->setPath('/new-path'); // Fragment may be lost; re-add if needed
      
  4. Port Omission

    • Default ports (e.g., 80 for HTTP) may not be included in output. Explicitly set if needed:
      $url->setPort(80); // Force inclusion
      
  5. Relative Path Resolution

    • Relative paths (e.g., ../parent) are resolved against the base URL, but edge cases (e.g., ../../../) may behave unexpectedly. Validate paths:
      $resolved = $base->resolve($relative);
      if (strpos($resolved->getPath(), '../') !== false) {
          throw new \InvalidArgumentException('Invalid relative path');
      }
      

Debugging Tips

  • Dump Parsed Parts Inspect all components for debugging:
    dd($url->getParts()); // Full breakdown of URL parts
    
  • Check for Deprecations The package is older (PEAR). Test against PHP 8.x for compatibility (e.g., array_key_first() may not work; use array_keys() instead).

Extension Points

  1. Custom Validation Extend with a validator trait or class:

    class ValidatedURL extends Net_URL2 {
        public function validate() {
            if (empty($this->getHost())) {
                throw new \InvalidArgumentException('Host is required');
            }
            return true;
        }
    }
    
  2. Hooks for Pre/Post-Operations Override methods like setParts() to add logic:

    class HookedURL extends Net_URL2 {
        public function setParts(array $parts) {
            $parts['scheme'] = strtolower($parts['scheme'] ?? '');
            return parent::setParts($parts);
        }
    }
    
  3. Integration with Laravel URL Helper Create a facade or helper to wrap Net_URL2:

    // app/Helpers/UrlHelper.php
    function parseUrl(string $url): array {
        $netUrl = new Net_URL2($url);
        return $netUrl->getParts();
    }
    
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.
calliostro/spotify-bundle
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle