Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Bundle/Form/SolidLoginType.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'constraints' => [new Callback(function (array $data, ExecutionContextInterface $context): void {
'constraints' => [new Callback(static function (array $data, ExecutionContextInterface $context): void {
$webId = $data['webid'] ?? '';
$op = $data['op'] ?? '';

Expand Down
150 changes: 150 additions & 0 deletions src/IriHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
<?php

/*
* This file is part of the Solid Client PHP project.
* (c) Kévin Dunglas <kevin@dunglas.fr>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Dunglas\PhpSolidClient;

/**
* RFC 3986 §5 relative IRI resolution.
*/
final class IriHelper
{
/**
* Resolves a relative reference against a base URI per RFC 3986 §5.3.
*/
public static function resolve(string $base, string $reference): string
{
// If the reference is already absolute, return it
$r = self::parse($reference);
if (null !== $r['scheme']) {
return self::recompose(
$r['scheme'],
$r['authority'],
self::removeDotSegments($r['path']),
$r['query'],
$r['fragment'],
);
}

$b = self::parse($base);

if (null !== $r['authority']) {
return self::recompose(
$b['scheme'],
$r['authority'],
self::removeDotSegments($r['path']),
$r['query'],
$r['fragment'],
);
}

if ('' === $r['path']) {
$path = $b['path'];
$query = $r['query'] ?? $b['query'];
} else {
if (str_starts_with($r['path'], '/')) {
$path = self::removeDotSegments($r['path']);
} else {
$path = self::merge($b, $r['path']);
$path = self::removeDotSegments($path);
}
$query = $r['query'];
}

return self::recompose($b['scheme'], $b['authority'], $path, $query, $r['fragment']);
}

/**
* @return array{scheme: ?string, authority: ?string, path: string, query: ?string, fragment: ?string}
*/
private static function parse(string $uri): array
{
// RFC 3986 Appendix B regex
preg_match('~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~', $uri, $m);

return [
'scheme' => isset($m[2]) && '' !== $m[2] ? $m[2] : null,
'authority' => isset($m[3]) && '' !== $m[3] ? $m[4] : null,
'path' => $m[5] ?? '',
'query' => isset($m[6]) && '' !== $m[6] ? $m[7] : null,
'fragment' => isset($m[8]) && '' !== $m[8] ? $m[9] : null,
];
}

/**
* @param array{scheme: ?string, authority: ?string, path: string, query: ?string, fragment: ?string} $base
*/
private static function merge(array $base, string $referencePath): string
{
if (null !== $base['authority'] && '' === $base['path']) {
return '/'.$referencePath;
}

$lastSlash = strrpos($base['path'], '/');

return false !== $lastSlash
? substr($base['path'], 0, $lastSlash + 1).$referencePath
: $referencePath;
}

private static function removeDotSegments(string $path): string
{
$output = [];
$segments = explode('/', $path);
$absolute = str_starts_with($path, '/');
$trailingSlash = false;

foreach ($segments as $segment) {
if ('.' === $segment) {
$trailingSlash = true;
continue;
}
if ('..' === $segment) {
array_pop($output);
$trailingSlash = true;
continue;
}
$trailingSlash = false;
$output[] = $segment;
}

$result = implode('/', $output);
if ($trailingSlash && !str_ends_with($result, '/')) {
$result .= '/';
}

// Preserve leading slash for absolute paths
if ($absolute && !str_starts_with($result, '/')) {
$result = '/'.$result;
}

return $result;
}

private static function recompose(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string
{
$result = '';
if (null !== $scheme) {
$result .= $scheme.':';
}
if (null !== $authority) {
$result .= '//'.$authority;
}
$result .= $path;
if (null !== $query) {
$result .= '?'.$query;
}
if (null !== $fragment) {
$result .= '#'.$fragment;
}

return $result;
}
}
64 changes: 64 additions & 0 deletions src/JsonLdParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

/*
* This file is part of the Solid Client PHP project.
* (c) Kévin Dunglas <kevin@dunglas.fr>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Dunglas\PhpSolidClient;

/**
* Parses JSON-LD responses from Solid/CSS servers.
*
* CSS returns expanded JSON-LD by default for Accept: application/ld+json,
* so a full JSON-LD processor is not needed — json_decode is sufficient.
* Relative @id values should be resolved using IriHelper.
*/
final class JsonLdParser
{
/**
* Parses a JSON-LD string into an array of node arrays.
*
* Handles both single objects and arrays of objects.
*
* @return list<array<string, mixed>>
*/
public static function parse(string $jsonLd): array
{
$decoded = json_decode($jsonLd, true, 512, \JSON_THROW_ON_ERROR);

// If it's a single object (has @id or @type), wrap in array
if (isset($decoded['@id']) || isset($decoded['@type'])) {
return [$decoded];
}

// If it's an array of objects (expanded form)
if (array_is_list($decoded)) {
return $decoded;
}

return [$decoded];
}

/**
* Finds a node by @id in parsed JSON-LD.
*
* @param list<array<string, mixed>> $nodes
*
* @return array<string, mixed>|null
*/
public static function findById(array $nodes, string $id): ?array
{
foreach ($nodes as $node) {
if (($node['@id'] ?? null) === $id) {
return $node;
}
}

return null;
}
}
80 changes: 80 additions & 0 deletions src/ResourceMetadata.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

/*
* This file is part of the Solid Client PHP project.
* (c) Kévin Dunglas <kevin@dunglas.fr>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Dunglas\PhpSolidClient;

final class ResourceMetadata
{
/**
* @param array<string, list<string>> $wacAllow parsed WAC-Allow header (e.g. ['user' => ['read', 'write'], 'public' => ['read']])
*/
public function __construct(
public readonly ?string $contentType = null,
public readonly ?int $contentLength = null,
public readonly ?\DateTimeImmutable $lastModified = null,
public readonly ?string $ldpType = null,
public readonly array $wacAllow = [],
public readonly ?string $aclUrl = null,
) {
}

public function isContainer(): bool
{
return 'http://www.w3.org/ns/ldp#BasicContainer' === $this->ldpType
|| 'http://www.w3.org/ns/ldp#Container' === $this->ldpType;
}

/**
* @param array<string, list<string>> $responseHeaders normalized response headers
*/
public static function fromResponseHeaders(array $responseHeaders): self
{
$contentType = isset($responseHeaders['content-type'][0])
? explode(';', $responseHeaders['content-type'][0], 2)[0]
: null;

$contentLength = isset($responseHeaders['content-length'][0])
? (int) $responseHeaders['content-length'][0]
: null;

$lastModified = isset($responseHeaders['last-modified'][0])
? \DateTimeImmutable::createFromFormat(\DateTimeInterface::RFC7231, $responseHeaders['last-modified'][0]) ?: null
: null;

$ldpType = null;
$aclUrl = null;
foreach ($responseHeaders['link'] ?? [] as $linkHeader) {
foreach (explode(',', $linkHeader) as $link) {
$link = trim($link);
if (preg_match('/<([^>]+)>;\s*rel="type"/', $link, $matches)) {
if (str_contains($matches[1], 'ldp#')) {
$ldpType = $matches[1];
}
}
if (preg_match('/<([^>]+)>;\s*rel="acl"/', $link, $matches)) {
$aclUrl = $matches[1];
}
}
}

$wacAllow = [];
if (isset($responseHeaders['wac-allow'][0])) {
// Format: user="read write append control",public="read"
if (preg_match_all('/(\w+)="([^"]*)"/', $responseHeaders['wac-allow'][0], $matches, \PREG_SET_ORDER)) {
foreach ($matches as $match) {
$wacAllow[$match[1]] = array_filter(explode(' ', $match[2]));
}
}
}

return new self($contentType, $contentLength, $lastModified, $ldpType, $wacAllow, $aclUrl);
}
}
48 changes: 44 additions & 4 deletions src/SolidClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function __construct(
) {
}

public function createContainer(string $parentUrl, string $name, string $data = null): ResponseInterface
public function createContainer(string $parentUrl, string $name, ?string $data = null): ResponseInterface
{
return $this->post($parentUrl, $data, $name, true);
}
Expand All @@ -41,7 +41,7 @@ public function createContainer(string $parentUrl, string $name, string $data =
*
* @see https://github.com/solid/solid-web-client/blob/main/src/client.js#L231=
*/
public function post(string $url, string $data = null, string $slug = null, bool $isContainer = false, array $options = []): ResponseInterface
public function post(string $url, ?string $data = null, ?string $slug = null, bool $isContainer = false, array $options = []): ResponseInterface
{
if ($isContainer || !isset($options['headers']['Content-Type'])) {
$options['headers']['Content-Type'] = self::DEFAULT_MIME_TYPE;
Expand All @@ -53,16 +53,56 @@ public function post(string $url, string $data = null, string $slug = null, bool
$options['headers']['Slug'] = $slug;
}

$options['headers']['Link'] = sprintf('<%s>; rel="type"', $isContainer ? self::LDP_BASIC_CONTAINER : self::LDP_RESOURCE);
$options['headers']['Link'] = \sprintf('<%s>; rel="type"', $isContainer ? self::LDP_BASIC_CONTAINER : self::LDP_RESOURCE);

return $this->request('POST', $url, $options);
}

public function put(string $url, ?string $data = null, bool $isContainer = false, array $options = []): ResponseInterface
{
if (!isset($options['headers']['Content-Type'])) {
$options['headers']['Content-Type'] = self::DEFAULT_MIME_TYPE;
}
if (null !== $data) {
$options['body'] = $data;
}
if ($isContainer) {
$options['headers']['Link'] = \sprintf('<%s>; rel="type"', self::LDP_BASIC_CONTAINER);
}

return $this->request('PUT', $url, $options);
}

public function get(string $url, array $options = []): ResponseInterface
{
return $this->request('GET', $url, $options);
}

public function head(string $url, array $options = []): ResponseInterface
{
return $this->request('HEAD', $url, $options);
}

public function delete(string $url, array $options = []): ResponseInterface
{
return $this->request('DELETE', $url, $options);
}

public function patch(string $url, string $data, string $contentType = 'application/sparql-update', array $options = []): ResponseInterface
{
$options['headers']['Content-Type'] = $contentType;
$options['body'] = $data;

return $this->request('PATCH', $url, $options);
}

public function getResourceMetadata(string $url, array $options = []): ResourceMetadata
{
$response = $this->head($url, $options);

return ResourceMetadata::fromResponseHeaders($response->getHeaders(false));
}

public function request(string $method, string $url, array $options = []): ResponseInterface
{
if ($accessToken = $this->oidcClient?->getAccessToken()) {
Expand All @@ -88,7 +128,7 @@ public function getOidcIssuer(string $webId, array $options = []): string
{
$graph = $this->getProfile($webId, $options);

$issuer = $graph->get($webId, sprintf('<%s>', self::OIDC_ISSUER))?->getUri();
$issuer = $graph->get($webId, \sprintf('<%s>', self::OIDC_ISSUER))?->getUri();
if (!\is_string($issuer)) {
throw new Exception('Unable to find the OIDC issuer associated with this WebID', 1);
}
Expand Down
2 changes: 1 addition & 1 deletion src/SolidClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public function __construct(private readonly HttpClientInterface $httpClient)
{
}

public function create(OidcClient $oidcClient = null): SolidClient
public function create(?OidcClient $oidcClient = null): SolidClient
{
return new SolidClient($this->httpClient, $oidcClient);
}
Expand Down
Loading