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

Iri Laravel Package

sweetrdf/iri

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require sweetrdf/iri
    
    • No additional configuration is required for basic usage.
  2. First Use Case: Validating & Normalizing IRIs

    use SweetRdf\Iri;
    
    // Create an IRI instance
    $iri = new Iri('http://example.com/path?query=value#fragment');
    
    // Check if it's valid
    if ($iri->isValid()) {
        echo "Valid IRI!";
    }
    
    // Normalize the IRI (expands %20, resolves relative paths, etc.)
    $normalized = $iri->getNormalized();
    
  3. Key Classes & Methods to Explore

    • SweetRdf\Iri: Core class for IRI manipulation.
    • SweetRdf\Iri\IriException: Exception handling.
    • SweetRdf\Iri\IriParser: Underlying parser logic (useful for custom extensions).

Implementation Patterns

Common Workflows

1. IRI Normalization in Laravel Models

  • Use IRIs as identifiers in Eloquent models (e.g., for linked data or semantic web apps).
use SweetRdf\Iri;

class KnowledgeGraphModel extends Model
{
    protected $iri;

    public function setIriAttribute($value)
    {
        $this->iri = (new Iri($value))->getNormalized();
    }

    public function getIriAttribute($value)
    {
        return $value;
    }
}

2. Validating API Inputs

  • Sanitize and validate IRIs in API requests (e.g., for SPARQL endpoints or RDF resources).
use SweetRdf\Iri;
use Illuminate\Http\Request;

public function store(Request $request)
{
    $iri = $request->input('iri');
    $normalizedIri = (new Iri($iri))->getNormalized();

    if (!$normalizedIri->isValid()) {
        throw new \InvalidArgumentException("Invalid IRI format.");
    }

    // Proceed with normalized IRI
}

3. Resolving Relative IRIs

  • Handle base URIs and relative paths (e.g., for RDF/XML or Turtle files).
$baseIri = new Iri('http://example.com/base/');
$relativeIri = new Iri('subpath#fragment', $baseIri);

echo $relativeIri->getNormalized(); // Outputs: http://example.com/base/subpath#fragment

4. Integration with SPARQL Clients

  • Normalize IRIs before sending to a SPARQL endpoint (e.g., using zazuko/graphql-php or rubix/ml).
$query = "SELECT ?s WHERE { ?s <http://example.com/predicate> ?o }";
$normalizedQuery = str_replace(
    'http://example.com/predicate',
    (new Iri('http://example.com/predicate'))->getNormalized(),
    $query
);

Laravel-Specific Tips

Service Provider Binding

  • Register the IRI class as a singleton for dependency injection.
// app/Providers/AppServiceProvider.php
public function register()
{
    $this->app->singleton(Iri::class, function () {
        return new Iri();
    });
}

Form Request Validation

  • Extend Laravel's validation with custom IRI rules.
use Illuminate\Validation\Rule;
use SweetRdf\Iri;

Rule::macro('valid_iri', function ($attribute, $value, $parameters) {
    return (new Iri($value))->isValid();
});

// Usage in FormRequest
$this->rules = [
    'iri' => ['required', 'valid_iri'],
];

Caching Normalized IRIs

  • Cache normalized IRIs to avoid redundant parsing (e.g., in a Repository class).
use Illuminate\Support\Facades\Cache;

public function getNormalizedIri($iriString, $ttl = 3600)
{
    return Cache::remember("iri_{$iriString}", $ttl, function () use ($iriString) {
        return (new Iri($iriString))->getNormalized();
    });
}

Gotchas and Tips

Pitfalls

1. Percent-Encoding Quirks

  • The package normalizes percent-encoded characters (e.g., %20 ), but some systems expect raw encoding.
  • Fix: Use getCanonical() instead of getNormalized() if you need strict percent-encoding.
$iri = new Iri('http://example.com/path%20with%20spaces');
echo $iri->getCanonical(); // Preserves %20

2. Fragment Handling

  • Fragments (#fragment) are not normalized by default (e.g., #foo vs #FOO are treated as different).
  • Tip: Use getNormalizedFragment() if case-insensitive fragments are needed.
$iri = new Iri('http://example.com#Foo');
echo $iri->getNormalizedFragment(); // Outputs: foo

3. Relative IRI Base Resolution

  • Relative IRIs (e.g., subpath) must be resolved against a base IRI or they’ll throw an exception.
  • Fix: Always provide a base IRI for relative paths.
$base = new Iri('http://example.com/base/');
$relative = new Iri('subpath', $base); // Works
$invalid = new Iri('subpath'); // Throws IriException

4. Internationalized Domain Names (IDNs)

  • The package does not automatically convert IDNs (e.g., 例.测试) to Punycode.
  • Workaround: Pre-process domains using idn_to_ascii().
$iri = new Iri('http://' . idn_to_ascii('例.测试') . '/path');

5. Query/Fragment Parsing Edge Cases

  • Query strings (?key=value) and fragments (#fragment) are parsed but not validated for correctness.
  • Tip: Use getQuery() and getFragment() to inspect/modify them separately.
$iri = new Iri('http://example.com?invalid=query#fragment');
$iri->setQuery('valid=query'); // Override query

Debugging Tips

1. Enable Strict Mode

  • Use setStrictMode(true) to catch invalid IRIs early.
$iri = new Iri('not an iri');
$iri->setStrictMode(true);
$iri->getNormalized(); // Throws IriException

2. Inspect Parsed Components

  • Break down an IRI into its components for debugging.
$iri = new Iri('http://user:pass@example.com:8080/path?query=value#fragment');
dump([
    'scheme' => $iri->getScheme(),
    'userinfo' => $iri->getUserInfo(),
    'host' => $iri->getHost(),
    'port' => $iri->getPort(),
    'path' => $iri->getPath(),
    'query' => $iri->getQuery(),
    'fragment' => $iri->getFragment(),
]);

3. Logging Invalid IRIs

  • Log malformed IRIs to track issues in production.
try {
    $iri = new Iri($userInput);
    $normalized = $iri->getNormalized();
} catch (IriException $e) {
    \Log::error("Invalid IRI submitted: {$userInput}", ['exception' => $e]);
    throw new \RuntimeException('Invalid IRI format.');
}

Extension Points

1. Custom IRI Validation

  • Extend the parser to enforce domain-specific rules (e.g., allow only certain TLDs).
use SweetRdf\Iri\IriParser;

class CustomIriParser extends IriParser
{
    protected function validateHost($host)
    {
        if (!preg_match('/\.allowed-tld$/', $host)) {
            throw new IriException("Host must end with .allowed-tld");
        }
        return parent::validateHost($host);
    }
}

// Usage
$iri = new Iri('http://example.allowed-tld', null, new CustomIriParser());

2. Adding Custom Schemes

  • Support non-standard schemes (e.g., mailto:, data:).
$iri = new Iri('mailto:user@example.com');
echo $iri->getScheme(); // Outputs: mailto
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky