repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/mime/Header/IdentificationHeader.php | vendor/symfony/mime/Header/IdentificationHeader.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Mime\Header;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Exception\RfcComplianceException;
/**
* An ID MIME Header for something like Message-ID or Content-ID (one or more addresses).
*
* @author Chris Corbyn
*/
final class IdentificationHeader extends AbstractHeader
{
private array $ids = [];
private array $idsAsAddresses = [];
public function __construct(string $name, string|array $ids)
{
parent::__construct($name);
$this->setId($ids);
}
/**
* @param string|string[] $body a string ID or an array of IDs
*
* @throws RfcComplianceException
*/
public function setBody(mixed $body)
{
$this->setId($body);
}
public function getBody(): array
{
return $this->getIds();
}
/**
* Set the ID used in the value of this header.
*
* @param string|string[] $id
*
* @throws RfcComplianceException
*/
public function setId(string|array $id)
{
$this->setIds(\is_array($id) ? $id : [$id]);
}
/**
* Get the ID used in the value of this Header.
*
* If multiple IDs are set only the first is returned.
*/
public function getId(): ?string
{
return $this->ids[0] ?? null;
}
/**
* Set a collection of IDs to use in the value of this Header.
*
* @param string[] $ids
*
* @throws RfcComplianceException
*/
public function setIds(array $ids)
{
$this->ids = [];
$this->idsAsAddresses = [];
foreach ($ids as $id) {
$this->idsAsAddresses[] = new Address($id);
$this->ids[] = $id;
}
}
/**
* Get the list of IDs used in this Header.
*
* @return string[]
*/
public function getIds(): array
{
return $this->ids;
}
public function getBodyAsString(): string
{
$addrs = [];
foreach ($this->idsAsAddresses as $address) {
$addrs[] = '<'.$address->toString().'>';
}
return implode(' ', $addrs);
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/ResponseStreamInterface.php | vendor/symfony/http-client-contracts/ResponseStreamInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient;
/**
* Yields response chunks, returned by HttpClientInterface::stream().
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @extends \Iterator<ResponseInterface, ChunkInterface>
*/
interface ResponseStreamInterface extends \Iterator
{
public function key(): ResponseInterface;
public function current(): ChunkInterface;
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/ChunkInterface.php | vendor/symfony/http-client-contracts/ChunkInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
/**
* The interface of chunks returned by ResponseStreamInterface::current().
*
* When the chunk is first, last or timeout, the content MUST be empty.
* When an unchecked timeout or a network error occurs, a TransportExceptionInterface
* MUST be thrown by the destructor unless one was already thrown by another method.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface ChunkInterface
{
/**
* Tells when the idle timeout has been reached.
*
* @throws TransportExceptionInterface on a network error
*/
public function isTimeout(): bool;
/**
* Tells when headers just arrived.
*
* @throws TransportExceptionInterface on a network error or when the idle timeout is reached
*/
public function isFirst(): bool;
/**
* Tells when the body just completed.
*
* @throws TransportExceptionInterface on a network error or when the idle timeout is reached
*/
public function isLast(): bool;
/**
* Returns a [status code, headers] tuple when a 1xx status code was just received.
*
* @throws TransportExceptionInterface on a network error or when the idle timeout is reached
*/
public function getInformationalStatus(): ?array;
/**
* Returns the content of the response chunk.
*
* @throws TransportExceptionInterface on a network error or when the idle timeout is reached
*/
public function getContent(): string;
/**
* Returns the offset of the chunk in the response body.
*/
public function getOffset(): int;
/**
* In case of error, returns the message that describes it.
*/
public function getError(): ?string;
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/HttpClientInterface.php | vendor/symfony/http-client-contracts/HttpClientInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\Test\HttpClientTestCase;
/**
* Provides flexible methods for requesting HTTP resources synchronously or asynchronously.
*
* @see HttpClientTestCase for a reference test suite
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface HttpClientInterface
{
public const OPTIONS_DEFAULTS = [
'auth_basic' => null, // array|string - an array containing the username as first value, and optionally the
// password as the second one; or string like username:password - enabling HTTP Basic
// authentication (RFC 7617)
'auth_bearer' => null, // string - a token enabling HTTP Bearer authorization (RFC 6750)
'query' => [], // string[] - associative array of query string values to merge with the request's URL
'headers' => [], // iterable|string[]|string[][] - headers names provided as keys or as part of values
'body' => '', // array|string|resource|\Traversable|\Closure - the callback SHOULD yield a string
// smaller than the amount requested as argument; the empty string signals EOF; if
// an array is passed, it is meant as a form payload of field names and values
'json' => null, // mixed - if set, implementations MUST set the "body" option to the JSON-encoded
// value and set the "content-type" header to a JSON-compatible value if it is not
// explicitly defined in the headers option - typically "application/json"
'user_data' => null, // mixed - any extra data to attach to the request (scalar, callable, object...) that
// MUST be available via $response->getInfo('user_data') - not used internally
'max_redirects' => 20, // int - the maximum number of redirects to follow; a value lower than or equal to 0
// means redirects should not be followed; "Authorization" and "Cookie" headers MUST
// NOT follow except for the initial host name
'http_version' => null, // string - defaults to the best supported version, typically 1.1 or 2.0
'base_uri' => null, // string - the URI to resolve relative URLs, following rules in RFC 3986, section 2
'buffer' => true, // bool|resource|\Closure - whether the content of the response should be buffered or not,
// or a stream resource where the response body should be written,
// or a closure telling if/where the response should be buffered based on its headers
'on_progress' => null, // callable(int $dlNow, int $dlSize, array $info) - throwing any exceptions MUST abort
// the request; it MUST be called on DNS resolution, on arrival of headers and on
// completion; it SHOULD be called on upload/download of data and at least 1/s
'resolve' => [], // string[] - a map of host to IP address that SHOULD replace DNS resolution
'proxy' => null, // string - by default, the proxy-related env vars handled by curl SHOULD be honored
'no_proxy' => null, // string - a comma separated list of hosts that do not require a proxy to be reached
'timeout' => null, // float - the idle timeout - defaults to ini_get('default_socket_timeout')
'max_duration' => 0, // float - the maximum execution time for the request+response as a whole;
// a value lower than or equal to 0 means it is unlimited
'bindto' => '0', // string - the interface or the local socket to bind to
'verify_peer' => true, // see https://php.net/context.ssl for the following options
'verify_host' => true,
'cafile' => null,
'capath' => null,
'local_cert' => null,
'local_pk' => null,
'passphrase' => null,
'ciphers' => null,
'peer_fingerprint' => null,
'capture_peer_cert_chain' => false,
'extra' => [], // array - additional options that can be ignored if unsupported, unlike regular options
];
/**
* Requests an HTTP resource.
*
* Responses MUST be lazy, but their status code MUST be
* checked even if none of their public methods are called.
*
* Implementations are not required to support all options described above; they can also
* support more custom options; but in any case, they MUST throw a TransportExceptionInterface
* when an unsupported option is passed.
*
* @throws TransportExceptionInterface When an unsupported option is passed
*/
public function request(string $method, string $url, array $options = []): ResponseInterface;
/**
* Yields responses chunk by chunk as they complete.
*
* @param ResponseInterface|iterable<array-key, ResponseInterface> $responses One or more responses created by the current HTTP client
* @param float|null $timeout The idle timeout before yielding timeout chunks
*/
public function stream(ResponseInterface|iterable $responses, float $timeout = null): ResponseStreamInterface;
/**
* Returns a new instance of the client with new default options.
*/
public function withOptions(array $options): static;
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/ResponseInterface.php | vendor/symfony/http-client-contracts/ResponseInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
/**
* A (lazily retrieved) HTTP response.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface ResponseInterface
{
/**
* Gets the HTTP status code of the response.
*
* @throws TransportExceptionInterface when a network error occurs
*/
public function getStatusCode(): int;
/**
* Gets the HTTP headers of the response.
*
* @param bool $throw Whether an exception should be thrown on 3/4/5xx status codes
*
* @return string[][] The headers of the response keyed by header names in lowercase
*
* @throws TransportExceptionInterface When a network error occurs
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
* @throws ClientExceptionInterface On a 4xx when $throw is true
* @throws ServerExceptionInterface On a 5xx when $throw is true
*/
public function getHeaders(bool $throw = true): array;
/**
* Gets the response body as a string.
*
* @param bool $throw Whether an exception should be thrown on 3/4/5xx status codes
*
* @throws TransportExceptionInterface When a network error occurs
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
* @throws ClientExceptionInterface On a 4xx when $throw is true
* @throws ServerExceptionInterface On a 5xx when $throw is true
*/
public function getContent(bool $throw = true): string;
/**
* Gets the response body decoded as array, typically from a JSON payload.
*
* @param bool $throw Whether an exception should be thrown on 3/4/5xx status codes
*
* @throws DecodingExceptionInterface When the body cannot be decoded to an array
* @throws TransportExceptionInterface When a network error occurs
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
* @throws ClientExceptionInterface On a 4xx when $throw is true
* @throws ServerExceptionInterface On a 5xx when $throw is true
*/
public function toArray(bool $throw = true): array;
/**
* Closes the response stream and all related buffers.
*
* No further chunk will be yielded after this method has been called.
*/
public function cancel(): void;
/**
* Returns info coming from the transport layer.
*
* This method SHOULD NOT throw any ExceptionInterface and SHOULD be non-blocking.
* The returned info is "live": it can be empty and can change from one call to
* another, as the request/response progresses.
*
* The following info MUST be returned:
* - canceled (bool) - true if the response was canceled using ResponseInterface::cancel(), false otherwise
* - error (string|null) - the error message when the transfer was aborted, null otherwise
* - http_code (int) - the last response code or 0 when it is not known yet
* - http_method (string) - the HTTP verb of the last request
* - redirect_count (int) - the number of redirects followed while executing the request
* - redirect_url (string|null) - the resolved location of redirect responses, null otherwise
* - response_headers (array) - an array modelled after the special $http_response_header variable
* - start_time (float) - the time when the request was sent or 0.0 when it's pending
* - url (string) - the last effective URL of the request
* - user_data (mixed) - the value of the "user_data" request option, null if not set
*
* When the "capture_peer_cert_chain" option is true, the "peer_certificate_chain"
* attribute SHOULD list the peer certificates as an array of OpenSSL X.509 resources.
*
* Other info SHOULD be named after curl_getinfo()'s associative return value.
*
* @return mixed An array of all available info, or one of them when $type is
* provided, or null when an unsupported type is requested
*/
public function getInfo(string $type = null): mixed;
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Test/HttpClientTestCase.php | vendor/symfony/http-client-contracts/Test/HttpClientTestCase.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Test;
use PHPUnit\Framework\TestCase;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TimeoutExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* A reference test suite for HttpClientInterface implementations.
*/
abstract class HttpClientTestCase extends TestCase
{
public static function setUpBeforeClass(): void
{
TestHttpServer::start();
}
abstract protected function getHttpClient(string $testCase): HttpClientInterface;
public function testGetRequest()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057', [
'headers' => ['Foo' => 'baR'],
'user_data' => $data = new \stdClass(),
]);
$this->assertSame([], $response->getInfo('response_headers'));
$this->assertSame($data, $response->getInfo()['user_data']);
$this->assertSame(200, $response->getStatusCode());
$info = $response->getInfo();
$this->assertNull($info['error']);
$this->assertSame(0, $info['redirect_count']);
$this->assertSame('HTTP/1.1 200 OK', $info['response_headers'][0]);
$this->assertSame('Host: localhost:8057', $info['response_headers'][1]);
$this->assertSame('http://localhost:8057/', $info['url']);
$headers = $response->getHeaders();
$this->assertSame('localhost:8057', $headers['host'][0]);
$this->assertSame(['application/json'], $headers['content-type']);
$body = json_decode($response->getContent(), true);
$this->assertSame($body, $response->toArray());
$this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
$this->assertSame('/', $body['REQUEST_URI']);
$this->assertSame('GET', $body['REQUEST_METHOD']);
$this->assertSame('localhost:8057', $body['HTTP_HOST']);
$this->assertSame('baR', $body['HTTP_FOO']);
$response = $client->request('GET', 'http://localhost:8057/length-broken');
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testHeadRequest()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('HEAD', 'http://localhost:8057/head', [
'headers' => ['Foo' => 'baR'],
'user_data' => $data = new \stdClass(),
'buffer' => false,
]);
$this->assertSame([], $response->getInfo('response_headers'));
$this->assertSame(200, $response->getStatusCode());
$info = $response->getInfo();
$this->assertSame('HTTP/1.1 200 OK', $info['response_headers'][0]);
$this->assertSame('Host: localhost:8057', $info['response_headers'][1]);
$headers = $response->getHeaders();
$this->assertSame('localhost:8057', $headers['host'][0]);
$this->assertSame(['application/json'], $headers['content-type']);
$this->assertTrue(0 < $headers['content-length'][0]);
$this->assertSame('', $response->getContent());
}
public function testNonBufferedGetRequest()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057', [
'buffer' => false,
'headers' => ['Foo' => 'baR'],
]);
$body = $response->toArray();
$this->assertSame('baR', $body['HTTP_FOO']);
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testBufferSink()
{
$sink = fopen('php://temp', 'w+');
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057', [
'buffer' => $sink,
'headers' => ['Foo' => 'baR'],
]);
$body = $response->toArray();
$this->assertSame('baR', $body['HTTP_FOO']);
rewind($sink);
$sink = stream_get_contents($sink);
$this->assertSame($sink, $response->getContent());
}
public function testConditionalBuffering()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057');
$firstContent = $response->getContent();
$secondContent = $response->getContent();
$this->assertSame($firstContent, $secondContent);
$response = $client->request('GET', 'http://localhost:8057', ['buffer' => function () { return false; }]);
$response->getContent();
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testReentrantBufferCallback()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057', ['buffer' => function () use (&$response) {
$response->cancel();
return true;
}]);
$this->assertSame(200, $response->getStatusCode());
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testThrowingBufferCallback()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057', ['buffer' => function () {
throw new \Exception('Boo.');
}]);
$this->assertSame(200, $response->getStatusCode());
$this->expectException(TransportExceptionInterface::class);
$this->expectExceptionMessage('Boo');
$response->getContent();
}
public function testUnsupportedOption()
{
$client = $this->getHttpClient(__FUNCTION__);
$this->expectException(\InvalidArgumentException::class);
$client->request('GET', 'http://localhost:8057', [
'capture_peer_cert' => 1.0,
]);
}
public function testHttpVersion()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057', [
'http_version' => 1.0,
]);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('HTTP/1.0 200 OK', $response->getInfo('response_headers')[0]);
$body = $response->toArray();
$this->assertSame('HTTP/1.0', $body['SERVER_PROTOCOL']);
$this->assertSame('GET', $body['REQUEST_METHOD']);
$this->assertSame('/', $body['REQUEST_URI']);
}
public function testChunkedEncoding()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/chunked');
$this->assertSame(['chunked'], $response->getHeaders()['transfer-encoding']);
$this->assertSame('Symfony is awesome!', $response->getContent());
$response = $client->request('GET', 'http://localhost:8057/chunked-broken');
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testClientError()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/404');
$client->stream($response)->valid();
$this->assertSame(404, $response->getInfo('http_code'));
try {
$response->getHeaders();
$this->fail(ClientExceptionInterface::class.' expected');
} catch (ClientExceptionInterface $e) {
}
try {
$response->getContent();
$this->fail(ClientExceptionInterface::class.' expected');
} catch (ClientExceptionInterface $e) {
}
$this->assertSame(404, $response->getStatusCode());
$this->assertSame(['application/json'], $response->getHeaders(false)['content-type']);
$this->assertNotEmpty($response->getContent(false));
$response = $client->request('GET', 'http://localhost:8057/404');
try {
foreach ($client->stream($response) as $chunk) {
$this->assertTrue($chunk->isFirst());
}
$this->fail(ClientExceptionInterface::class.' expected');
} catch (ClientExceptionInterface $e) {
}
}
public function testIgnoreErrors()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/404');
$this->assertSame(404, $response->getStatusCode());
}
public function testDnsError()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/301/bad-tld');
try {
$response->getStatusCode();
$this->fail(TransportExceptionInterface::class.' expected');
} catch (TransportExceptionInterface $e) {
$this->addToAssertionCount(1);
}
try {
$response->getStatusCode();
$this->fail(TransportExceptionInterface::class.' still expected');
} catch (TransportExceptionInterface $e) {
$this->addToAssertionCount(1);
}
$response = $client->request('GET', 'http://localhost:8057/301/bad-tld');
try {
foreach ($client->stream($response) as $r => $chunk) {
}
$this->fail(TransportExceptionInterface::class.' expected');
} catch (TransportExceptionInterface $e) {
$this->addToAssertionCount(1);
}
$this->assertSame($response, $r);
$this->assertNotNull($chunk->getError());
$this->expectException(TransportExceptionInterface::class);
foreach ($client->stream($response) as $chunk) {
}
}
public function testInlineAuth()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://foo:bar%3Dbar@localhost:8057');
$body = $response->toArray();
$this->assertSame('foo', $body['PHP_AUTH_USER']);
$this->assertSame('bar=bar', $body['PHP_AUTH_PW']);
}
public function testBadRequestBody()
{
$client = $this->getHttpClient(__FUNCTION__);
$this->expectException(TransportExceptionInterface::class);
$response = $client->request('POST', 'http://localhost:8057/', [
'body' => function () { yield []; },
]);
$response->getStatusCode();
}
public function test304()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/304', [
'headers' => ['If-Match' => '"abc"'],
'buffer' => false,
]);
$this->assertSame(304, $response->getStatusCode());
$this->assertSame('', $response->getContent(false));
}
public function testRedirects()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/301', [
'auth_basic' => 'foo:bar',
'body' => function () {
yield 'foo=bar';
},
]);
$body = $response->toArray();
$this->assertSame('GET', $body['REQUEST_METHOD']);
$this->assertSame('Basic Zm9vOmJhcg==', $body['HTTP_AUTHORIZATION']);
$this->assertSame('http://localhost:8057/', $response->getInfo('url'));
$this->assertSame(2, $response->getInfo('redirect_count'));
$this->assertNull($response->getInfo('redirect_url'));
$expected = [
'HTTP/1.1 301 Moved Permanently',
'Location: http://127.0.0.1:8057/302',
'Content-Type: application/json',
'HTTP/1.1 302 Found',
'Location: http://localhost:8057/',
'Content-Type: application/json',
'HTTP/1.1 200 OK',
'Content-Type: application/json',
];
$filteredHeaders = array_values(array_filter($response->getInfo('response_headers'), function ($h) {
return \in_array(substr($h, 0, 4), ['HTTP', 'Loca', 'Cont'], true) && 'Content-Encoding: gzip' !== $h;
}));
$this->assertSame($expected, $filteredHeaders);
}
public function testInvalidRedirect()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/301/invalid');
$this->assertSame(301, $response->getStatusCode());
$this->assertSame(['//?foo=bar'], $response->getHeaders(false)['location']);
$this->assertSame(0, $response->getInfo('redirect_count'));
$this->assertNull($response->getInfo('redirect_url'));
$this->expectException(RedirectionExceptionInterface::class);
$response->getHeaders();
}
public function testRelativeRedirects()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/302/relative');
$body = $response->toArray();
$this->assertSame('/', $body['REQUEST_URI']);
$this->assertNull($response->getInfo('redirect_url'));
$response = $client->request('GET', 'http://localhost:8057/302/relative', [
'max_redirects' => 0,
]);
$this->assertSame(302, $response->getStatusCode());
$this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url'));
}
public function testRedirect307()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/307', [
'body' => function () {
yield 'foo=bar';
},
'max_redirects' => 0,
]);
$this->assertSame(307, $response->getStatusCode());
$response = $client->request('POST', 'http://localhost:8057/307', [
'body' => 'foo=bar',
]);
$body = $response->toArray();
$this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $body);
}
public function testMaxRedirects()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/301', [
'max_redirects' => 1,
'auth_basic' => 'foo:bar',
]);
try {
$response->getHeaders();
$this->fail(RedirectionExceptionInterface::class.' expected');
} catch (RedirectionExceptionInterface $e) {
}
$this->assertSame(302, $response->getStatusCode());
$this->assertSame(1, $response->getInfo('redirect_count'));
$this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url'));
$expected = [
'HTTP/1.1 301 Moved Permanently',
'Location: http://127.0.0.1:8057/302',
'Content-Type: application/json',
'HTTP/1.1 302 Found',
'Location: http://localhost:8057/',
'Content-Type: application/json',
];
$filteredHeaders = array_values(array_filter($response->getInfo('response_headers'), function ($h) {
return \in_array(substr($h, 0, 4), ['HTTP', 'Loca', 'Cont'], true);
}));
$this->assertSame($expected, $filteredHeaders);
}
public function testStream()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057');
$chunks = $client->stream($response);
$result = [];
foreach ($chunks as $r => $chunk) {
if ($chunk->isTimeout()) {
$result[] = 't';
} elseif ($chunk->isLast()) {
$result[] = 'l';
} elseif ($chunk->isFirst()) {
$result[] = 'f';
}
}
$this->assertSame($response, $r);
$this->assertSame(['f', 'l'], $result);
$chunk = null;
$i = 0;
foreach ($client->stream($response) as $chunk) {
++$i;
}
$this->assertSame(1, $i);
$this->assertTrue($chunk->isLast());
}
public function testAddToStream()
{
$client = $this->getHttpClient(__FUNCTION__);
$r1 = $client->request('GET', 'http://localhost:8057');
$completed = [];
$pool = [$r1];
while ($pool) {
$chunks = $client->stream($pool);
$pool = [];
foreach ($chunks as $r => $chunk) {
if (!$chunk->isLast()) {
continue;
}
if ($r1 === $r) {
$r2 = $client->request('GET', 'http://localhost:8057');
$pool[] = $r2;
}
$completed[] = $r;
}
}
$this->assertSame([$r1, $r2], $completed);
}
public function testCompleteTypeError()
{
$client = $this->getHttpClient(__FUNCTION__);
$this->expectException(\TypeError::class);
$client->stream(123);
}
public function testOnProgress()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/post', [
'headers' => ['Content-Length' => 14],
'body' => 'foo=0123456789',
'on_progress' => function (...$state) use (&$steps) { $steps[] = $state; },
]);
$body = $response->toArray();
$this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $body);
$this->assertSame([0, 0], \array_slice($steps[0], 0, 2));
$lastStep = \array_slice($steps, -1)[0];
$this->assertSame([57, 57], \array_slice($lastStep, 0, 2));
$this->assertSame('http://localhost:8057/post', $steps[0][2]['url']);
}
public function testPostJson()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/post', [
'json' => ['foo' => 'bar'],
]);
$body = $response->toArray();
$this->assertStringContainsString('json', $body['content-type']);
unset($body['content-type']);
$this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $body);
}
public function testPostArray()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/post', [
'body' => ['foo' => 'bar'],
]);
$this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $response->toArray());
}
public function testPostResource()
{
$client = $this->getHttpClient(__FUNCTION__);
$h = fopen('php://temp', 'w+');
fwrite($h, 'foo=0123456789');
rewind($h);
$response = $client->request('POST', 'http://localhost:8057/post', [
'body' => $h,
]);
$body = $response->toArray();
$this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $body);
}
public function testPostCallback()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/post', [
'body' => function () {
yield 'foo';
yield '';
yield '=';
yield '0123456789';
},
]);
$this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $response->toArray());
}
public function testCancel()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-header');
$response->cancel();
$this->expectException(TransportExceptionInterface::class);
$response->getHeaders();
}
public function testInfoOnCanceledResponse()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-header');
$this->assertFalse($response->getInfo('canceled'));
$response->cancel();
$this->assertTrue($response->getInfo('canceled'));
}
public function testCancelInStream()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/404');
foreach ($client->stream($response) as $chunk) {
$response->cancel();
}
$this->expectException(TransportExceptionInterface::class);
foreach ($client->stream($response) as $chunk) {
}
}
public function testOnProgressCancel()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-body', [
'on_progress' => function ($dlNow) {
if (0 < $dlNow) {
throw new \Exception('Aborting the request.');
}
},
]);
try {
foreach ($client->stream([$response]) as $chunk) {
}
$this->fail(ClientExceptionInterface::class.' expected');
} catch (TransportExceptionInterface $e) {
$this->assertSame('Aborting the request.', $e->getPrevious()->getMessage());
}
$this->assertNotNull($response->getInfo('error'));
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testOnProgressError()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-body', [
'on_progress' => function ($dlNow) {
if (0 < $dlNow) {
throw new \Error('BUG.');
}
},
]);
try {
foreach ($client->stream([$response]) as $chunk) {
}
$this->fail('Error expected');
} catch (\Error $e) {
$this->assertSame('BUG.', $e->getMessage());
}
$this->assertNotNull($response->getInfo('error'));
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testResolve()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://symfony.com:8057/', [
'resolve' => ['symfony.com' => '127.0.0.1'],
]);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame(200, $client->request('GET', 'http://symfony.com:8057/')->getStatusCode());
$response = null;
$this->expectException(TransportExceptionInterface::class);
$client->request('GET', 'http://symfony.com:8057/', ['timeout' => 1]);
}
public function testIdnResolve()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://0-------------------------------------------------------------0.com:8057/', [
'resolve' => ['0-------------------------------------------------------------0.com' => '127.0.0.1'],
]);
$this->assertSame(200, $response->getStatusCode());
$response = $client->request('GET', 'http://Bücher.example:8057/', [
'resolve' => ['xn--bcher-kva.example' => '127.0.0.1'],
]);
$this->assertSame(200, $response->getStatusCode());
}
public function testNotATimeout()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-header', [
'timeout' => 0.9,
]);
sleep(1);
$this->assertSame(200, $response->getStatusCode());
}
public function testTimeoutOnAccess()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-header', [
'timeout' => 0.1,
]);
$this->expectException(TransportExceptionInterface::class);
$response->getHeaders();
}
public function testTimeoutIsNotAFatalError()
{
usleep(300000); // wait for the previous test to release the server
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-body', [
'timeout' => 0.25,
]);
try {
$response->getContent();
$this->fail(TimeoutExceptionInterface::class.' expected');
} catch (TimeoutExceptionInterface $e) {
}
for ($i = 0; $i < 10; ++$i) {
try {
$this->assertSame('<1><2>', $response->getContent());
break;
} catch (TimeoutExceptionInterface $e) {
}
}
if (10 === $i) {
throw $e;
}
}
public function testTimeoutOnStream()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-body');
$this->assertSame(200, $response->getStatusCode());
$chunks = $client->stream([$response], 0.2);
$result = [];
foreach ($chunks as $r => $chunk) {
if ($chunk->isTimeout()) {
$result[] = 't';
} else {
$result[] = $chunk->getContent();
}
}
$this->assertSame(['<1>', 't'], $result);
$chunks = $client->stream([$response]);
foreach ($chunks as $r => $chunk) {
$this->assertSame('<2>', $chunk->getContent());
$this->assertSame('<1><2>', $r->getContent());
return;
}
$this->fail('The response should have completed');
}
public function testUncheckedTimeoutThrows()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-body');
$chunks = $client->stream([$response], 0.1);
$this->expectException(TransportExceptionInterface::class);
foreach ($chunks as $r => $chunk) {
}
}
public function testTimeoutWithActiveConcurrentStream()
{
$p1 = TestHttpServer::start(8067);
$p2 = TestHttpServer::start(8077);
$client = $this->getHttpClient(__FUNCTION__);
$streamingResponse = $client->request('GET', 'http://localhost:8067/max-duration');
$blockingResponse = $client->request('GET', 'http://localhost:8077/timeout-body', [
'timeout' => 0.25,
]);
$this->assertSame(200, $streamingResponse->getStatusCode());
$this->assertSame(200, $blockingResponse->getStatusCode());
$this->expectException(TransportExceptionInterface::class);
try {
$blockingResponse->getContent();
} finally {
$p1->stop();
$p2->stop();
}
}
public function testTimeoutOnDestruct()
{
$p1 = TestHttpServer::start(8067);
$p2 = TestHttpServer::start(8077);
$client = $this->getHttpClient(__FUNCTION__);
$start = microtime(true);
$responses = [];
$responses[] = $client->request('GET', 'http://localhost:8067/timeout-header', ['timeout' => 0.25]);
$responses[] = $client->request('GET', 'http://localhost:8077/timeout-header', ['timeout' => 0.25]);
$responses[] = $client->request('GET', 'http://localhost:8067/timeout-header', ['timeout' => 0.25]);
$responses[] = $client->request('GET', 'http://localhost:8077/timeout-header', ['timeout' => 0.25]);
try {
while ($response = array_shift($responses)) {
try {
unset($response);
$this->fail(TransportExceptionInterface::class.' expected');
} catch (TransportExceptionInterface $e) {
}
}
$duration = microtime(true) - $start;
$this->assertLessThan(1.0, $duration);
} finally {
$p1->stop();
$p2->stop();
}
}
public function testDestruct()
{
$client = $this->getHttpClient(__FUNCTION__);
$start = microtime(true);
$client->request('GET', 'http://localhost:8057/timeout-long');
$client = null;
$duration = microtime(true) - $start;
$this->assertGreaterThan(1, $duration);
$this->assertLessThan(4, $duration);
}
public function testGetContentAfterDestruct()
{
$client = $this->getHttpClient(__FUNCTION__);
try {
$client->request('GET', 'http://localhost:8057/404');
$this->fail(ClientExceptionInterface::class.' expected');
} catch (ClientExceptionInterface $e) {
$this->assertSame('GET', $e->getResponse()->toArray(false)['REQUEST_METHOD']);
}
}
public function testGetEncodedContentAfterDestruct()
{
$client = $this->getHttpClient(__FUNCTION__);
try {
$client->request('GET', 'http://localhost:8057/404-gzipped');
$this->fail(ClientExceptionInterface::class.' expected');
} catch (ClientExceptionInterface $e) {
$this->assertSame('some text', $e->getResponse()->getContent(false));
}
}
public function testProxy()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/', [
'proxy' => 'http://localhost:8057',
]);
$body = $response->toArray();
$this->assertSame('localhost:8057', $body['HTTP_HOST']);
$this->assertMatchesRegularExpression('#^http://(localhost|127\.0\.0\.1):8057/$#', $body['REQUEST_URI']);
$response = $client->request('GET', 'http://localhost:8057/', [
'proxy' => 'http://foo:b%3Dar@localhost:8057',
]);
$body = $response->toArray();
$this->assertSame('Basic Zm9vOmI9YXI=', $body['HTTP_PROXY_AUTHORIZATION']);
}
public function testNoProxy()
{
putenv('no_proxy='.$_SERVER['no_proxy'] = 'example.com, localhost');
try {
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/', [
'proxy' => 'http://localhost:8057',
]);
$body = $response->toArray();
$this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
$this->assertSame('/', $body['REQUEST_URI']);
$this->assertSame('GET', $body['REQUEST_METHOD']);
} finally {
putenv('no_proxy');
unset($_SERVER['no_proxy']);
}
}
/**
* @requires extension zlib
*/
public function testAutoEncodingRequest()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057');
$this->assertSame(200, $response->getStatusCode());
$headers = $response->getHeaders();
$this->assertSame(['Accept-Encoding'], $headers['vary']);
$this->assertStringContainsString('gzip', $headers['content-encoding'][0]);
$body = $response->toArray();
$this->assertStringContainsString('gzip', $body['HTTP_ACCEPT_ENCODING']);
}
public function testBaseUri()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', '../404', [
'base_uri' => 'http://localhost:8057/abc/',
]);
$this->assertSame(404, $response->getStatusCode());
$this->assertSame(['application/json'], $response->getHeaders(false)['content-type']);
}
public function testQuery()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/?a=a', [
'query' => ['b' => 'b'],
]);
$body = $response->toArray();
$this->assertSame('GET', $body['REQUEST_METHOD']);
$this->assertSame('/?a=a&b=b', $body['REQUEST_URI']);
}
public function testInformationalResponse()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/103');
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | true |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Test/TestHttpServer.php | vendor/symfony/http-client-contracts/Test/TestHttpServer.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Test;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
class TestHttpServer
{
private static $process = [];
public static function start(int $port = 8057): Process
{
if (isset(self::$process[$port])) {
self::$process[$port]->stop();
} else {
register_shutdown_function(static function () use ($port) {
self::$process[$port]->stop();
});
}
$finder = new PhpExecutableFinder();
$process = new Process(array_merge([$finder->find(false)], $finder->findArguments(), ['-dopcache.enable=0', '-dvariables_order=EGPCS', '-S', '127.0.0.1:'.$port]));
$process->setWorkingDirectory(__DIR__.'/Fixtures/web');
$process->start();
self::$process[$port] = $process;
do {
usleep(50000);
} while (!@fopen('http://127.0.0.1:'.$port, 'r'));
return $process;
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Test/Fixtures/web/index.php | vendor/symfony/http-client-contracts/Test/Fixtures/web/index.php | <?php
if ('cli-server' !== \PHP_SAPI) {
// safe guard against unwanted execution
throw new \Exception("You cannot run this script directly, it's a fixture for TestHttpServer.");
}
$vars = [];
if (!$_POST) {
$_POST = json_decode(file_get_contents('php://input'), true);
$_POST['content-type'] = $_SERVER['HTTP_CONTENT_TYPE'] ?? '?';
}
foreach ($_SERVER as $k => $v) {
switch ($k) {
default:
if (0 !== strpos($k, 'HTTP_')) {
continue 2;
}
// no break
case 'SERVER_NAME':
case 'SERVER_PROTOCOL':
case 'REQUEST_URI':
case 'REQUEST_METHOD':
case 'PHP_AUTH_USER':
case 'PHP_AUTH_PW':
$vars[$k] = $v;
}
}
$json = json_encode($vars, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE);
switch ($vars['REQUEST_URI']) {
default:
exit;
case '/head':
header('Content-Length: '.strlen($json), true);
break;
case '/':
case '/?a=a&b=b':
case 'http://127.0.0.1:8057/':
case 'http://localhost:8057/':
ob_start('ob_gzhandler');
break;
case '/103':
header('HTTP/1.1 103 Early Hints');
header('Link: </style.css>; rel=preload; as=style', false);
header('Link: </script.js>; rel=preload; as=script', false);
flush();
usleep(1000);
echo "HTTP/1.1 200 OK\r\n";
echo "Date: Fri, 26 May 2017 10:02:11 GMT\r\n";
echo "Content-Length: 13\r\n";
echo "\r\n";
echo 'Here the body';
exit;
case '/404':
header('Content-Type: application/json', true, 404);
break;
case '/404-gzipped':
header('Content-Type: text/plain', true, 404);
ob_start('ob_gzhandler');
@ob_flush();
flush();
usleep(300000);
echo 'some text';
exit;
case '/301':
if ('Basic Zm9vOmJhcg==' === $vars['HTTP_AUTHORIZATION']) {
header('Location: http://127.0.0.1:8057/302', true, 301);
}
break;
case '/301/bad-tld':
header('Location: http://foo.example.', true, 301);
break;
case '/301/invalid':
header('Location: //?foo=bar', true, 301);
break;
case '/302':
if (!isset($vars['HTTP_AUTHORIZATION'])) {
header('Location: http://localhost:8057/', true, 302);
}
break;
case '/302/relative':
header('Location: ..', true, 302);
break;
case '/304':
header('Content-Length: 10', true, 304);
echo '12345';
return;
case '/307':
header('Location: http://localhost:8057/post', true, 307);
break;
case '/length-broken':
header('Content-Length: 1000');
break;
case '/post':
$output = json_encode($_POST + ['REQUEST_METHOD' => $vars['REQUEST_METHOD']], \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE);
header('Content-Type: application/json', true);
header('Content-Length: '.strlen($output));
echo $output;
exit;
case '/timeout-header':
usleep(300000);
break;
case '/timeout-body':
echo '<1>';
@ob_flush();
flush();
usleep(500000);
echo '<2>';
exit;
case '/timeout-long':
ignore_user_abort(false);
sleep(1);
while (true) {
echo '<1>';
@ob_flush();
flush();
usleep(500);
}
exit;
case '/chunked':
header('Transfer-Encoding: chunked');
echo "8\r\nSymfony \r\n5\r\nis aw\r\n6\r\nesome!\r\n0\r\n\r\n";
exit;
case '/chunked-broken':
header('Transfer-Encoding: chunked');
echo "8\r\nSymfony \r\n5\r\nis aw\r\n6\r\ne";
exit;
case '/gzip-broken':
header('Content-Encoding: gzip');
echo str_repeat('-', 1000);
exit;
case '/max-duration':
ignore_user_abort(false);
while (true) {
echo '<1>';
@ob_flush();
flush();
usleep(500);
}
exit;
case '/json':
header('Content-Type: application/json');
echo json_encode([
'documents' => [
['id' => '/json/1'],
['id' => '/json/2'],
['id' => '/json/3'],
],
]);
exit;
case '/json/1':
case '/json/2':
case '/json/3':
header('Content-Type: application/json');
echo json_encode([
'title' => $vars['REQUEST_URI'],
]);
exit;
}
header('Content-Type: application/json', true);
echo $json;
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Exception/HttpExceptionInterface.php | vendor/symfony/http-client-contracts/Exception/HttpExceptionInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
use Symfony\Contracts\HttpClient\ResponseInterface;
/**
* Base interface for HTTP-related exceptions.
*
* @author Anton Chernikov <anton_ch1989@mail.ru>
*/
interface HttpExceptionInterface extends ExceptionInterface
{
public function getResponse(): ResponseInterface;
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Exception/TransportExceptionInterface.php | vendor/symfony/http-client-contracts/Exception/TransportExceptionInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* When any error happens at the transport level.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface TransportExceptionInterface extends ExceptionInterface
{
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Exception/ServerExceptionInterface.php | vendor/symfony/http-client-contracts/Exception/ServerExceptionInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* When a 5xx response is returned.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface ServerExceptionInterface extends HttpExceptionInterface
{
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Exception/RedirectionExceptionInterface.php | vendor/symfony/http-client-contracts/Exception/RedirectionExceptionInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* When a 3xx response is returned and the "max_redirects" option has been reached.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface RedirectionExceptionInterface extends HttpExceptionInterface
{
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Exception/ExceptionInterface.php | vendor/symfony/http-client-contracts/Exception/ExceptionInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* The base interface for all exceptions in the contract.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface ExceptionInterface extends \Throwable
{
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Exception/TimeoutExceptionInterface.php | vendor/symfony/http-client-contracts/Exception/TimeoutExceptionInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* When an idle timeout occurs.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface TimeoutExceptionInterface extends TransportExceptionInterface
{
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Exception/ClientExceptionInterface.php | vendor/symfony/http-client-contracts/Exception/ClientExceptionInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* When a 4xx response is returned.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface ClientExceptionInterface extends HttpExceptionInterface
{
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/http-client-contracts/Exception/DecodingExceptionInterface.php | vendor/symfony/http-client-contracts/Exception/DecodingExceptionInterface.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* When a content-type cannot be decoded to the expected representation.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface DecodingExceptionInterface extends ExceptionInterface
{
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Link.php | vendor/symfony/dom-crawler/Link.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler;
/**
* Link represents an HTML link (an HTML a, area or link tag).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Link extends AbstractUriElement
{
protected function getRawUri(): string
{
return $this->node->getAttribute('href');
}
protected function setNode(\DOMElement $node)
{
if ('a' !== $node->nodeName && 'area' !== $node->nodeName && 'link' !== $node->nodeName) {
throw new \LogicException(sprintf('Unable to navigate from a "%s" tag.', $node->nodeName));
}
$this->node = $node;
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Image.php | vendor/symfony/dom-crawler/Image.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler;
/**
* Image represents an HTML image (an HTML img tag).
*/
class Image extends AbstractUriElement
{
public function __construct(\DOMElement $node, string $currentUri = null)
{
parent::__construct($node, $currentUri, 'GET');
}
protected function getRawUri(): string
{
return $this->node->getAttribute('src');
}
protected function setNode(\DOMElement $node)
{
if ('img' !== $node->nodeName) {
throw new \LogicException(sprintf('Unable to visualize a "%s" tag.', $node->nodeName));
}
$this->node = $node;
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/AbstractUriElement.php | vendor/symfony/dom-crawler/AbstractUriElement.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler;
/**
* Any HTML element that can link to an URI.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class AbstractUriElement
{
/**
* @var \DOMElement
*/
protected $node;
/**
* @var string|null The method to use for the element
*/
protected $method;
/**
* @var string The URI of the page where the element is embedded (or the base href)
*/
protected $currentUri;
/**
* @param \DOMElement $node A \DOMElement instance
* @param string|null $currentUri The URI of the page where the link is embedded (or the base href)
* @param string|null $method The method to use for the link (GET by default)
*
* @throws \InvalidArgumentException if the node is not a link
*/
public function __construct(\DOMElement $node, string $currentUri = null, ?string $method = 'GET')
{
$this->setNode($node);
$this->method = $method ? strtoupper($method) : null;
$this->currentUri = $currentUri;
$elementUriIsRelative = null === parse_url(trim($this->getRawUri()), \PHP_URL_SCHEME);
$baseUriIsAbsolute = null !== $this->currentUri && \in_array(strtolower(substr($this->currentUri, 0, 4)), ['http', 'file']);
if ($elementUriIsRelative && !$baseUriIsAbsolute) {
throw new \InvalidArgumentException(sprintf('The URL of the element is relative, so you must define its base URI passing an absolute URL to the constructor of the "%s" class ("%s" was passed).', __CLASS__, $this->currentUri));
}
}
/**
* Gets the node associated with this link.
*/
public function getNode(): \DOMElement
{
return $this->node;
}
/**
* Gets the method associated with this link.
*/
public function getMethod(): string
{
return $this->method ?? 'GET';
}
/**
* Gets the URI associated with this link.
*/
public function getUri(): string
{
return UriResolver::resolve($this->getRawUri(), $this->currentUri);
}
/**
* Returns raw URI data.
*/
abstract protected function getRawUri(): string;
/**
* Returns the canonicalized URI path (see RFC 3986, section 5.2.4).
*
* @param string $path URI path
*/
protected function canonicalizePath(string $path): string
{
if ('' === $path || '/' === $path) {
return $path;
}
if (str_ends_with($path, '.')) {
$path .= '/';
}
$output = [];
foreach (explode('/', $path) as $segment) {
if ('..' === $segment) {
array_pop($output);
} elseif ('.' !== $segment) {
$output[] = $segment;
}
}
return implode('/', $output);
}
/**
* Sets current \DOMElement instance.
*
* @param \DOMElement $node A \DOMElement instance
*
* @throws \LogicException If given node is not an anchor
*/
abstract protected function setNode(\DOMElement $node);
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Crawler.php | vendor/symfony/dom-crawler/Crawler.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler;
use Masterminds\HTML5;
use Symfony\Component\CssSelector\CssSelectorConverter;
/**
* Crawler eases navigation of a list of \DOMNode objects.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @implements \IteratorAggregate<int, \DOMNode>
*/
class Crawler implements \Countable, \IteratorAggregate
{
/**
* @var string|null
*/
protected $uri;
/**
* The default namespace prefix to be used with XPath and CSS expressions.
*/
private string $defaultNamespacePrefix = 'default';
/**
* A map of manually registered namespaces.
*
* @var array<string, string>
*/
private array $namespaces = [];
/**
* A map of cached namespaces.
*/
private \ArrayObject $cachedNamespaces;
private ?string $baseHref;
private ?\DOMDocument $document = null;
/**
* @var list<\DOMNode>
*/
private array $nodes = [];
/**
* Whether the Crawler contains HTML or XML content (used when converting CSS to XPath).
*/
private bool $isHtml = true;
private $html5Parser;
/**
* @param \DOMNodeList|\DOMNode|\DOMNode[]|string|null $node A Node to use as the base for the crawling
*/
public function __construct(\DOMNodeList|\DOMNode|array|string $node = null, string $uri = null, string $baseHref = null)
{
$this->uri = $uri;
$this->baseHref = $baseHref ?: $uri;
$this->html5Parser = class_exists(HTML5::class) ? new HTML5(['disable_html_ns' => true]) : null;
$this->cachedNamespaces = new \ArrayObject();
$this->add($node);
}
/**
* Returns the current URI.
*/
public function getUri(): ?string
{
return $this->uri;
}
/**
* Returns base href.
*/
public function getBaseHref(): ?string
{
return $this->baseHref;
}
/**
* Removes all the nodes.
*/
public function clear()
{
$this->nodes = [];
$this->document = null;
$this->cachedNamespaces = new \ArrayObject();
}
/**
* Adds a node to the current list of nodes.
*
* This method uses the appropriate specialized add*() method based
* on the type of the argument.
*
* @param \DOMNodeList|\DOMNode|\DOMNode[]|string|null $node A node
*
* @throws \InvalidArgumentException when node is not the expected type
*/
public function add(\DOMNodeList|\DOMNode|array|string|null $node)
{
if ($node instanceof \DOMNodeList) {
$this->addNodeList($node);
} elseif ($node instanceof \DOMNode) {
$this->addNode($node);
} elseif (\is_array($node)) {
$this->addNodes($node);
} elseif (\is_string($node)) {
$this->addContent($node);
} elseif (null !== $node) {
throw new \InvalidArgumentException(sprintf('Expecting a DOMNodeList or DOMNode instance, an array, a string, or null, but got "%s".', get_debug_type($node)));
}
}
/**
* Adds HTML/XML content.
*
* If the charset is not set via the content type, it is assumed to be UTF-8,
* or ISO-8859-1 as a fallback, which is the default charset defined by the
* HTTP 1.1 specification.
*/
public function addContent(string $content, string $type = null)
{
if (empty($type)) {
$type = str_starts_with($content, '<?xml') ? 'application/xml' : 'text/html';
}
// DOM only for HTML/XML content
if (!preg_match('/(x|ht)ml/i', $type, $xmlMatches)) {
return;
}
$charset = null;
if (false !== $pos = stripos($type, 'charset=')) {
$charset = substr($type, $pos + 8);
if (false !== $pos = strpos($charset, ';')) {
$charset = substr($charset, 0, $pos);
}
}
// http://www.w3.org/TR/encoding/#encodings
// http://www.w3.org/TR/REC-xml/#NT-EncName
if (null === $charset &&
preg_match('/\<meta[^\>]+charset *= *["\']?([a-zA-Z\-0-9_:.]+)/i', $content, $matches)) {
$charset = $matches[1];
}
if (null === $charset) {
$charset = preg_match('//u', $content) ? 'UTF-8' : 'ISO-8859-1';
}
if ('x' === $xmlMatches[1]) {
$this->addXmlContent($content, $charset);
} else {
$this->addHtmlContent($content, $charset);
}
}
/**
* Adds an HTML content to the list of nodes.
*
* The libxml errors are disabled when the content is parsed.
*
* If you want to get parsing errors, be sure to enable
* internal errors via libxml_use_internal_errors(true)
* and then, get the errors via libxml_get_errors(). Be
* sure to clear errors with libxml_clear_errors() afterward.
*/
public function addHtmlContent(string $content, string $charset = 'UTF-8')
{
$dom = $this->parseHtmlString($content, $charset);
$this->addDocument($dom);
$base = $this->filterRelativeXPath('descendant-or-self::base')->extract(['href']);
$baseHref = current($base);
if (\count($base) && !empty($baseHref)) {
if ($this->baseHref) {
$linkNode = $dom->createElement('a');
$linkNode->setAttribute('href', $baseHref);
$link = new Link($linkNode, $this->baseHref);
$this->baseHref = $link->getUri();
} else {
$this->baseHref = $baseHref;
}
}
}
/**
* Adds an XML content to the list of nodes.
*
* The libxml errors are disabled when the content is parsed.
*
* If you want to get parsing errors, be sure to enable
* internal errors via libxml_use_internal_errors(true)
* and then, get the errors via libxml_get_errors(). Be
* sure to clear errors with libxml_clear_errors() afterward.
*
* @param int $options Bitwise OR of the libxml option constants
* LIBXML_PARSEHUGE is dangerous, see
* http://symfony.com/blog/security-release-symfony-2-0-17-released
*/
public function addXmlContent(string $content, string $charset = 'UTF-8', int $options = \LIBXML_NONET)
{
// remove the default namespace if it's the only namespace to make XPath expressions simpler
if (!preg_match('/xmlns:/', $content)) {
$content = str_replace('xmlns', 'ns', $content);
}
$internalErrors = libxml_use_internal_errors(true);
$dom = new \DOMDocument('1.0', $charset);
$dom->validateOnParse = true;
if ('' !== trim($content)) {
@$dom->loadXML($content, $options);
}
libxml_use_internal_errors($internalErrors);
$this->addDocument($dom);
$this->isHtml = false;
}
/**
* Adds a \DOMDocument to the list of nodes.
*
* @param \DOMDocument $dom A \DOMDocument instance
*/
public function addDocument(\DOMDocument $dom)
{
if ($dom->documentElement) {
$this->addNode($dom->documentElement);
}
}
/**
* Adds a \DOMNodeList to the list of nodes.
*
* @param \DOMNodeList $nodes A \DOMNodeList instance
*/
public function addNodeList(\DOMNodeList $nodes)
{
foreach ($nodes as $node) {
if ($node instanceof \DOMNode) {
$this->addNode($node);
}
}
}
/**
* Adds an array of \DOMNode instances to the list of nodes.
*
* @param \DOMNode[] $nodes An array of \DOMNode instances
*/
public function addNodes(array $nodes)
{
foreach ($nodes as $node) {
$this->add($node);
}
}
/**
* Adds a \DOMNode instance to the list of nodes.
*
* @param \DOMNode $node A \DOMNode instance
*/
public function addNode(\DOMNode $node)
{
if ($node instanceof \DOMDocument) {
$node = $node->documentElement;
}
if (null !== $this->document && $this->document !== $node->ownerDocument) {
throw new \InvalidArgumentException('Attaching DOM nodes from multiple documents in the same crawler is forbidden.');
}
if (null === $this->document) {
$this->document = $node->ownerDocument;
}
// Don't add duplicate nodes in the Crawler
if (\in_array($node, $this->nodes, true)) {
return;
}
$this->nodes[] = $node;
}
/**
* Returns a node given its position in the node list.
*/
public function eq(int $position): static
{
if (isset($this->nodes[$position])) {
return $this->createSubCrawler($this->nodes[$position]);
}
return $this->createSubCrawler(null);
}
/**
* Calls an anonymous function on each node of the list.
*
* The anonymous function receives the position and the node wrapped
* in a Crawler instance as arguments.
*
* Example:
*
* $crawler->filter('h1')->each(function ($node, $i) {
* return $node->text();
* });
*
* @param \Closure $closure An anonymous function
*
* @return array An array of values returned by the anonymous function
*/
public function each(\Closure $closure): array
{
$data = [];
foreach ($this->nodes as $i => $node) {
$data[] = $closure($this->createSubCrawler($node), $i);
}
return $data;
}
/**
* Slices the list of nodes by $offset and $length.
*/
public function slice(int $offset = 0, int $length = null): static
{
return $this->createSubCrawler(\array_slice($this->nodes, $offset, $length));
}
/**
* Reduces the list of nodes by calling an anonymous function.
*
* To remove a node from the list, the anonymous function must return false.
*
* @param \Closure $closure An anonymous function
*/
public function reduce(\Closure $closure): static
{
$nodes = [];
foreach ($this->nodes as $i => $node) {
if (false !== $closure($this->createSubCrawler($node), $i)) {
$nodes[] = $node;
}
}
return $this->createSubCrawler($nodes);
}
/**
* Returns the first node of the current selection.
*/
public function first(): static
{
return $this->eq(0);
}
/**
* Returns the last node of the current selection.
*/
public function last(): static
{
return $this->eq(\count($this->nodes) - 1);
}
/**
* Returns the siblings nodes of the current selection.
*
* @throws \InvalidArgumentException When current node is empty
*/
public function siblings(): static
{
if (!$this->nodes) {
throw new \InvalidArgumentException('The current node list is empty.');
}
return $this->createSubCrawler($this->sibling($this->getNode(0)->parentNode->firstChild));
}
public function matches(string $selector): bool
{
if (!$this->nodes) {
return false;
}
$converter = $this->createCssSelectorConverter();
$xpath = $converter->toXPath($selector, 'self::');
return 0 !== $this->filterRelativeXPath($xpath)->count();
}
/**
* Return first parents (heading toward the document root) of the Element that matches the provided selector.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
*
* @throws \InvalidArgumentException When current node is empty
*/
public function closest(string $selector): ?self
{
if (!$this->nodes) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$domNode = $this->getNode(0);
while (\XML_ELEMENT_NODE === $domNode->nodeType) {
$node = $this->createSubCrawler($domNode);
if ($node->matches($selector)) {
return $node;
}
$domNode = $node->getNode(0)->parentNode;
}
return null;
}
/**
* Returns the next siblings nodes of the current selection.
*
* @throws \InvalidArgumentException When current node is empty
*/
public function nextAll(): static
{
if (!$this->nodes) {
throw new \InvalidArgumentException('The current node list is empty.');
}
return $this->createSubCrawler($this->sibling($this->getNode(0)));
}
/**
* Returns the previous sibling nodes of the current selection.
*
* @throws \InvalidArgumentException
*/
public function previousAll(): static
{
if (!$this->nodes) {
throw new \InvalidArgumentException('The current node list is empty.');
}
return $this->createSubCrawler($this->sibling($this->getNode(0), 'previousSibling'));
}
/**
* Returns the ancestors of the current selection.
*
* @throws \InvalidArgumentException When the current node is empty
*/
public function ancestors(): static
{
if (!$this->nodes) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$node = $this->getNode(0);
$nodes = [];
while ($node = $node->parentNode) {
if (\XML_ELEMENT_NODE === $node->nodeType) {
$nodes[] = $node;
}
}
return $this->createSubCrawler($nodes);
}
/**
* Returns the children nodes of the current selection.
*
* @throws \InvalidArgumentException When current node is empty
* @throws \RuntimeException If the CssSelector Component is not available and $selector is provided
*/
public function children(string $selector = null): static
{
if (!$this->nodes) {
throw new \InvalidArgumentException('The current node list is empty.');
}
if (null !== $selector) {
$converter = $this->createCssSelectorConverter();
$xpath = $converter->toXPath($selector, 'child::');
return $this->filterRelativeXPath($xpath);
}
$node = $this->getNode(0)->firstChild;
return $this->createSubCrawler($node ? $this->sibling($node) : []);
}
/**
* Returns the attribute value of the first node of the list.
*
* @throws \InvalidArgumentException When current node is empty
*/
public function attr(string $attribute): ?string
{
if (!$this->nodes) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$node = $this->getNode(0);
return $node->hasAttribute($attribute) ? $node->getAttribute($attribute) : null;
}
/**
* Returns the node name of the first node of the list.
*
* @throws \InvalidArgumentException When current node is empty
*/
public function nodeName(): string
{
if (!$this->nodes) {
throw new \InvalidArgumentException('The current node list is empty.');
}
return $this->getNode(0)->nodeName;
}
/**
* Returns the text of the first node of the list.
*
* Pass true as the second argument to normalize whitespaces.
*
* @param string|null $default When not null: the value to return when the current node is empty
* @param bool $normalizeWhitespace Whether whitespaces should be trimmed and normalized to single spaces
*
* @throws \InvalidArgumentException When current node is empty
*/
public function text(string $default = null, bool $normalizeWhitespace = true): string
{
if (!$this->nodes) {
if (null !== $default) {
return $default;
}
throw new \InvalidArgumentException('The current node list is empty.');
}
$text = $this->getNode(0)->nodeValue;
if ($normalizeWhitespace) {
return trim(preg_replace('/(?:\s{2,}+|[^\S ])/', ' ', $text));
}
return $text;
}
/**
* Returns only the inner text that is the direct descendent of the current node, excluding any child nodes.
*/
public function innerText(): string
{
return $this->filterXPath('.//text()')->text();
}
/**
* Returns the first node of the list as HTML.
*
* @param string|null $default When not null: the value to return when the current node is empty
*
* @throws \InvalidArgumentException When current node is empty
*/
public function html(string $default = null): string
{
if (!$this->nodes) {
if (null !== $default) {
return $default;
}
throw new \InvalidArgumentException('The current node list is empty.');
}
$node = $this->getNode(0);
$owner = $node->ownerDocument;
if (null !== $this->html5Parser && '<!DOCTYPE html>' === $owner->saveXML($owner->childNodes[0])) {
$owner = $this->html5Parser;
}
$html = '';
foreach ($node->childNodes as $child) {
$html .= $owner->saveHTML($child);
}
return $html;
}
public function outerHtml(): string
{
if (!\count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$node = $this->getNode(0);
$owner = $node->ownerDocument;
if (null !== $this->html5Parser && '<!DOCTYPE html>' === $owner->saveXML($owner->childNodes[0])) {
$owner = $this->html5Parser;
}
return $owner->saveHTML($node);
}
/**
* Evaluates an XPath expression.
*
* Since an XPath expression might evaluate to either a simple type or a \DOMNodeList,
* this method will return either an array of simple types or a new Crawler instance.
*
* @return array|Crawler
*/
public function evaluate(string $xpath): array|Crawler
{
if (null === $this->document) {
throw new \LogicException('Cannot evaluate the expression on an uninitialized crawler.');
}
$data = [];
$domxpath = $this->createDOMXPath($this->document, $this->findNamespacePrefixes($xpath));
foreach ($this->nodes as $node) {
$data[] = $domxpath->evaluate($xpath, $node);
}
if (isset($data[0]) && $data[0] instanceof \DOMNodeList) {
return $this->createSubCrawler($data);
}
return $data;
}
/**
* Extracts information from the list of nodes.
*
* You can extract attributes or/and the node value (_text).
*
* Example:
*
* $crawler->filter('h1 a')->extract(['_text', 'href']);
*/
public function extract(array $attributes): array
{
$count = \count($attributes);
$data = [];
foreach ($this->nodes as $node) {
$elements = [];
foreach ($attributes as $attribute) {
if ('_text' === $attribute) {
$elements[] = $node->nodeValue;
} elseif ('_name' === $attribute) {
$elements[] = $node->nodeName;
} else {
$elements[] = $node->getAttribute($attribute);
}
}
$data[] = 1 === $count ? $elements[0] : $elements;
}
return $data;
}
/**
* Filters the list of nodes with an XPath expression.
*
* The XPath expression is evaluated in the context of the crawler, which
* is considered as a fake parent of the elements inside it.
* This means that a child selector "div" or "./div" will match only
* the div elements of the current crawler, not their children.
*/
public function filterXPath(string $xpath): static
{
$xpath = $this->relativize($xpath);
// If we dropped all expressions in the XPath while preparing it, there would be no match
if ('' === $xpath) {
return $this->createSubCrawler(null);
}
return $this->filterRelativeXPath($xpath);
}
/**
* Filters the list of nodes with a CSS selector.
*
* This method only works if you have installed the CssSelector Symfony Component.
*
* @throws \RuntimeException if the CssSelector Component is not available
*/
public function filter(string $selector): static
{
$converter = $this->createCssSelectorConverter();
// The CssSelector already prefixes the selector with descendant-or-self::
return $this->filterRelativeXPath($converter->toXPath($selector));
}
/**
* Selects links by name or alt value for clickable images.
*/
public function selectLink(string $value): static
{
return $this->filterRelativeXPath(
sprintf('descendant-or-self::a[contains(concat(\' \', normalize-space(string(.)), \' \'), %1$s) or ./img[contains(concat(\' \', normalize-space(string(@alt)), \' \'), %1$s)]]', static::xpathLiteral(' '.$value.' '))
);
}
/**
* Selects images by alt value.
*/
public function selectImage(string $value): static
{
$xpath = sprintf('descendant-or-self::img[contains(normalize-space(string(@alt)), %s)]', static::xpathLiteral($value));
return $this->filterRelativeXPath($xpath);
}
/**
* Selects a button by name or alt value for images.
*/
public function selectButton(string $value): static
{
return $this->filterRelativeXPath(
sprintf('descendant-or-self::input[((contains(%1$s, "submit") or contains(%1$s, "button")) and contains(concat(\' \', normalize-space(string(@value)), \' \'), %2$s)) or (contains(%1$s, "image") and contains(concat(\' \', normalize-space(string(@alt)), \' \'), %2$s)) or @id=%3$s or @name=%3$s] | descendant-or-self::button[contains(concat(\' \', normalize-space(string(.)), \' \'), %2$s) or @id=%3$s or @name=%3$s]', 'translate(@type, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")', static::xpathLiteral(' '.$value.' '), static::xpathLiteral($value))
);
}
/**
* Returns a Link object for the first node in the list.
*
* @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
*/
public function link(string $method = 'get'): Link
{
if (!$this->nodes) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$node = $this->getNode(0);
if (!$node instanceof \DOMElement) {
throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', get_debug_type($node)));
}
return new Link($node, $this->baseHref, $method);
}
/**
* Returns an array of Link objects for the nodes in the list.
*
* @return Link[]
*
* @throws \InvalidArgumentException If the current node list contains non-DOMElement instances
*/
public function links(): array
{
$links = [];
foreach ($this->nodes as $node) {
if (!$node instanceof \DOMElement) {
throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', get_debug_type($node)));
}
$links[] = new Link($node, $this->baseHref, 'get');
}
return $links;
}
/**
* Returns an Image object for the first node in the list.
*
* @throws \InvalidArgumentException If the current node list is empty
*/
public function image(): Image
{
if (!\count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$node = $this->getNode(0);
if (!$node instanceof \DOMElement) {
throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', get_debug_type($node)));
}
return new Image($node, $this->baseHref);
}
/**
* Returns an array of Image objects for the nodes in the list.
*
* @return Image[]
*/
public function images(): array
{
$images = [];
foreach ($this as $node) {
if (!$node instanceof \DOMElement) {
throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', get_debug_type($node)));
}
$images[] = new Image($node, $this->baseHref);
}
return $images;
}
/**
* Returns a Form object for the first node in the list.
*
* @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
*/
public function form(array $values = null, string $method = null): Form
{
if (!$this->nodes) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$node = $this->getNode(0);
if (!$node instanceof \DOMElement) {
throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', get_debug_type($node)));
}
$form = new Form($node, $this->uri, $method, $this->baseHref);
if (null !== $values) {
$form->setValues($values);
}
return $form;
}
/**
* Overloads a default namespace prefix to be used with XPath and CSS expressions.
*/
public function setDefaultNamespacePrefix(string $prefix)
{
$this->defaultNamespacePrefix = $prefix;
}
public function registerNamespace(string $prefix, string $namespace)
{
$this->namespaces[$prefix] = $namespace;
}
/**
* Converts string for XPath expressions.
*
* Escaped characters are: quotes (") and apostrophe (').
*
* Examples:
*
* echo Crawler::xpathLiteral('foo " bar');
* //prints 'foo " bar'
*
* echo Crawler::xpathLiteral("foo ' bar");
* //prints "foo ' bar"
*
* echo Crawler::xpathLiteral('a\'b"c');
* //prints concat('a', "'", 'b"c')
*/
public static function xpathLiteral(string $s): string
{
if (!str_contains($s, "'")) {
return sprintf("'%s'", $s);
}
if (!str_contains($s, '"')) {
return sprintf('"%s"', $s);
}
$string = $s;
$parts = [];
while (true) {
if (false !== $pos = strpos($string, "'")) {
$parts[] = sprintf("'%s'", substr($string, 0, $pos));
$parts[] = "\"'\"";
$string = substr($string, $pos + 1);
} else {
$parts[] = "'$string'";
break;
}
}
return sprintf('concat(%s)', implode(', ', $parts));
}
/**
* Filters the list of nodes with an XPath expression.
*
* The XPath expression should already be processed to apply it in the context of each node.
*/
private function filterRelativeXPath(string $xpath): static
{
$crawler = $this->createSubCrawler(null);
if (null === $this->document) {
return $crawler;
}
$domxpath = $this->createDOMXPath($this->document, $this->findNamespacePrefixes($xpath));
foreach ($this->nodes as $node) {
$crawler->add($domxpath->query($xpath, $node));
}
return $crawler;
}
/**
* Make the XPath relative to the current context.
*
* The returned XPath will match elements matching the XPath inside the current crawler
* when running in the context of a node of the crawler.
*/
private function relativize(string $xpath): string
{
$expressions = [];
// An expression which will never match to replace expressions which cannot match in the crawler
// We cannot drop
$nonMatchingExpression = 'a[name() = "b"]';
$xpathLen = \strlen($xpath);
$openedBrackets = 0;
$startPosition = strspn($xpath, " \t\n\r\0\x0B");
for ($i = $startPosition; $i <= $xpathLen; ++$i) {
$i += strcspn($xpath, '"\'[]|', $i);
if ($i < $xpathLen) {
switch ($xpath[$i]) {
case '"':
case "'":
if (false === $i = strpos($xpath, $xpath[$i], $i + 1)) {
return $xpath; // The XPath expression is invalid
}
continue 2;
case '[':
++$openedBrackets;
continue 2;
case ']':
--$openedBrackets;
continue 2;
}
}
if ($openedBrackets) {
continue;
}
if ($startPosition < $xpathLen && '(' === $xpath[$startPosition]) {
// If the union is inside some braces, we need to preserve the opening braces and apply
// the change only inside it.
$j = 1 + strspn($xpath, "( \t\n\r\0\x0B", $startPosition + 1);
$parenthesis = substr($xpath, $startPosition, $j);
$startPosition += $j;
} else {
$parenthesis = '';
}
$expression = rtrim(substr($xpath, $startPosition, $i - $startPosition));
if (str_starts_with($expression, 'self::*/')) {
$expression = './'.substr($expression, 8);
}
// add prefix before absolute element selector
if ('' === $expression) {
$expression = $nonMatchingExpression;
} elseif (str_starts_with($expression, '//')) {
$expression = 'descendant-or-self::'.substr($expression, 2);
} elseif (str_starts_with($expression, './/')) {
$expression = 'descendant-or-self::'.substr($expression, 3);
} elseif (str_starts_with($expression, './')) {
$expression = 'self::'.substr($expression, 2);
} elseif (str_starts_with($expression, 'child::')) {
$expression = 'self::'.substr($expression, 7);
} elseif ('/' === $expression[0] || '.' === $expression[0] || str_starts_with($expression, 'self::')) {
$expression = $nonMatchingExpression;
} elseif (str_starts_with($expression, 'descendant::')) {
$expression = 'descendant-or-self::'.substr($expression, 12);
} elseif (preg_match('/^(ancestor|ancestor-or-self|attribute|following|following-sibling|namespace|parent|preceding|preceding-sibling)::/', $expression)) {
// the fake root has no parent, preceding or following nodes and also no attributes (even no namespace attributes)
$expression = $nonMatchingExpression;
} elseif (!str_starts_with($expression, 'descendant-or-self::')) {
$expression = 'self::'.$expression;
}
$expressions[] = $parenthesis.$expression;
if ($i === $xpathLen) {
return implode(' | ', $expressions);
}
$i += strspn($xpath, " \t\n\r\0\x0B", $i + 1);
$startPosition = $i + 1;
}
return $xpath; // The XPath expression is invalid
}
public function getNode(int $position): ?\DOMNode
{
return $this->nodes[$position] ?? null;
}
public function count(): int
{
return \count($this->nodes);
}
/**
* @return \ArrayIterator<int, \DOMNode>
*/
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator($this->nodes);
}
protected function sibling(\DOMNode $node, string $siblingDir = 'nextSibling'): array
{
$nodes = [];
$currentNode = $this->getNode(0);
do {
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | true |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/UriResolver.php | vendor/symfony/dom-crawler/UriResolver.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler;
/**
* The UriResolver class takes an URI (relative, absolute, fragment, etc.)
* and turns it into an absolute URI against another given base URI.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
class UriResolver
{
/**
* Resolves a URI according to a base URI.
*
* For example if $uri=/foo/bar and $baseUri=https://symfony.com it will
* return https://symfony.com/foo/bar
*
* If the $uri is not absolute you must pass an absolute $baseUri
*/
public static function resolve(string $uri, ?string $baseUri): string
{
$uri = trim($uri);
// absolute URL?
if (null !== parse_url($uri, \PHP_URL_SCHEME)) {
return $uri;
}
if (null === $baseUri) {
throw new \InvalidArgumentException('The URI is relative, so you must define its base URI passing an absolute URL.');
}
// empty URI
if (!$uri) {
return $baseUri;
}
// an anchor
if ('#' === $uri[0]) {
return self::cleanupAnchor($baseUri).$uri;
}
$baseUriCleaned = self::cleanupUri($baseUri);
if ('?' === $uri[0]) {
return $baseUriCleaned.$uri;
}
// absolute URL with relative schema
if (0 === strpos($uri, '//')) {
return preg_replace('#^([^/]*)//.*$#', '$1', $baseUriCleaned).$uri;
}
$baseUriCleaned = preg_replace('#^(.*?//[^/]*)(?:\/.*)?$#', '$1', $baseUriCleaned);
// absolute path
if ('/' === $uri[0]) {
return $baseUriCleaned.$uri;
}
// relative path
$path = parse_url(substr($baseUri, \strlen($baseUriCleaned)), \PHP_URL_PATH);
$path = self::canonicalizePath(substr($path, 0, strrpos($path, '/')).'/'.$uri);
return $baseUriCleaned.('' === $path || '/' !== $path[0] ? '/' : '').$path;
}
/**
* Returns the canonicalized URI path (see RFC 3986, section 5.2.4).
*/
private static function canonicalizePath(string $path): string
{
if ('' === $path || '/' === $path) {
return $path;
}
if ('.' === substr($path, -1)) {
$path .= '/';
}
$output = [];
foreach (explode('/', $path) as $segment) {
if ('..' === $segment) {
array_pop($output);
} elseif ('.' !== $segment) {
$output[] = $segment;
}
}
return implode('/', $output);
}
/**
* Removes the query string and the anchor from the given uri.
*/
private static function cleanupUri(string $uri): string
{
return self::cleanupQuery(self::cleanupAnchor($uri));
}
/**
* Removes the query string from the uri.
*/
private static function cleanupQuery(string $uri): string
{
if (false !== $pos = strpos($uri, '?')) {
return substr($uri, 0, $pos);
}
return $uri;
}
/**
* Removes the anchor from the uri.
*/
private static function cleanupAnchor(string $uri): string
{
if (false !== $pos = strpos($uri, '#')) {
return substr($uri, 0, $pos);
}
return $uri;
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Form.php | vendor/symfony/dom-crawler/Form.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler;
use Symfony\Component\DomCrawler\Field\ChoiceFormField;
use Symfony\Component\DomCrawler\Field\FormField;
/**
* Form represents an HTML form.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Form extends Link implements \ArrayAccess
{
private \DOMElement $button;
private $fields;
private ?string $baseHref;
/**
* @param \DOMElement $node A \DOMElement instance
* @param string|null $currentUri The URI of the page where the form is embedded
* @param string|null $method The method to use for the link (if null, it defaults to the method defined by the form)
* @param string|null $baseHref The URI of the <base> used for relative links, but not for empty action
*
* @throws \LogicException if the node is not a button inside a form tag
*/
public function __construct(\DOMElement $node, string $currentUri = null, string $method = null, string $baseHref = null)
{
parent::__construct($node, $currentUri, $method);
$this->baseHref = $baseHref;
$this->initialize();
}
/**
* Gets the form node associated with this form.
*/
public function getFormNode(): \DOMElement
{
return $this->node;
}
/**
* Sets the value of the fields.
*
* @param array $values An array of field values
*
* @return $this
*/
public function setValues(array $values): static
{
foreach ($values as $name => $value) {
$this->fields->set($name, $value);
}
return $this;
}
/**
* Gets the field values.
*
* The returned array does not include file fields (@see getFiles).
*/
public function getValues(): array
{
$values = [];
foreach ($this->fields->all() as $name => $field) {
if ($field->isDisabled()) {
continue;
}
if (!$field instanceof Field\FileFormField && $field->hasValue()) {
$values[$name] = $field->getValue();
}
}
return $values;
}
/**
* Gets the file field values.
*/
public function getFiles(): array
{
if (!\in_array($this->getMethod(), ['POST', 'PUT', 'DELETE', 'PATCH'])) {
return [];
}
$files = [];
foreach ($this->fields->all() as $name => $field) {
if ($field->isDisabled()) {
continue;
}
if ($field instanceof Field\FileFormField) {
$files[$name] = $field->getValue();
}
}
return $files;
}
/**
* Gets the field values as PHP.
*
* This method converts fields with the array notation
* (like foo[bar] to arrays) like PHP does.
*/
public function getPhpValues(): array
{
$values = [];
foreach ($this->getValues() as $name => $value) {
$qs = http_build_query([$name => $value], '', '&');
if (!empty($qs)) {
parse_str($qs, $expandedValue);
$varName = substr($name, 0, \strlen(key($expandedValue)));
$values[] = [$varName => current($expandedValue)];
}
}
return array_replace_recursive([], ...$values);
}
/**
* Gets the file field values as PHP.
*
* This method converts fields with the array notation
* (like foo[bar] to arrays) like PHP does.
* The returned array is consistent with the array for field values
* (@see getPhpValues), rather than uploaded files found in $_FILES.
* For a compound file field foo[bar] it will create foo[bar][name],
* instead of foo[name][bar] which would be found in $_FILES.
*/
public function getPhpFiles(): array
{
$values = [];
foreach ($this->getFiles() as $name => $value) {
$qs = http_build_query([$name => $value], '', '&');
if (!empty($qs)) {
parse_str($qs, $expandedValue);
$varName = substr($name, 0, \strlen(key($expandedValue)));
array_walk_recursive(
$expandedValue,
function (&$value, $key) {
if (ctype_digit($value) && ('size' === $key || 'error' === $key)) {
$value = (int) $value;
}
}
);
reset($expandedValue);
$values[] = [$varName => current($expandedValue)];
}
}
return array_replace_recursive([], ...$values);
}
/**
* Gets the URI of the form.
*
* The returned URI is not the same as the form "action" attribute.
* This method merges the value if the method is GET to mimics
* browser behavior.
*/
public function getUri(): string
{
$uri = parent::getUri();
if (!\in_array($this->getMethod(), ['POST', 'PUT', 'DELETE', 'PATCH'])) {
$query = parse_url($uri, \PHP_URL_QUERY);
$currentParameters = [];
if ($query) {
parse_str($query, $currentParameters);
}
$queryString = http_build_query(array_merge($currentParameters, $this->getValues()), '', '&');
$pos = strpos($uri, '?');
$base = false === $pos ? $uri : substr($uri, 0, $pos);
$uri = rtrim($base.'?'.$queryString, '?');
}
return $uri;
}
protected function getRawUri(): string
{
// If the form was created from a button rather than the form node, check for HTML5 action overrides
if ($this->button !== $this->node && $this->button->getAttribute('formaction')) {
return $this->button->getAttribute('formaction');
}
return $this->node->getAttribute('action');
}
/**
* Gets the form method.
*
* If no method is defined in the form, GET is returned.
*/
public function getMethod(): string
{
if (null !== $this->method) {
return $this->method;
}
// If the form was created from a button rather than the form node, check for HTML5 method override
if ($this->button !== $this->node && $this->button->getAttribute('formmethod')) {
return strtoupper($this->button->getAttribute('formmethod'));
}
return $this->node->getAttribute('method') ? strtoupper($this->node->getAttribute('method')) : 'GET';
}
/**
* Gets the form name.
*
* If no name is defined on the form, an empty string is returned.
*/
public function getName(): string
{
return $this->node->getAttribute('name');
}
/**
* Returns true if the named field exists.
*/
public function has(string $name): bool
{
return $this->fields->has($name);
}
/**
* Removes a field from the form.
*/
public function remove(string $name)
{
$this->fields->remove($name);
}
/**
* Gets a named field.
*
* @return FormField|FormField[]|FormField[][]
*
* @throws \InvalidArgumentException When field is not present in this form
*/
public function get(string $name): FormField|array
{
return $this->fields->get($name);
}
/**
* Sets a named field.
*/
public function set(FormField $field)
{
$this->fields->add($field);
}
/**
* Gets all fields.
*
* @return FormField[]
*/
public function all(): array
{
return $this->fields->all();
}
/**
* Returns true if the named field exists.
*
* @param string $name The field name
*/
public function offsetExists(mixed $name): bool
{
return $this->has($name);
}
/**
* Gets the value of a field.
*
* @param string $name The field name
*
* @return FormField|FormField[]|FormField[][]
*
* @throws \InvalidArgumentException if the field does not exist
*/
public function offsetGet(mixed $name): FormField|array
{
return $this->fields->get($name);
}
/**
* Sets the value of a field.
*
* @param string $name The field name
* @param string|array $value The value of the field
*
* @throws \InvalidArgumentException if the field does not exist
*/
public function offsetSet(mixed $name, mixed $value): void
{
$this->fields->set($name, $value);
}
/**
* Removes a field from the form.
*
* @param string $name The field name
*/
public function offsetUnset(mixed $name): void
{
$this->fields->remove($name);
}
/**
* Disables validation.
*
* @return $this
*/
public function disableValidation(): static
{
foreach ($this->fields->all() as $field) {
if ($field instanceof Field\ChoiceFormField) {
$field->disableValidation();
}
}
return $this;
}
/**
* Sets the node for the form.
*
* Expects a 'submit' button \DOMElement and finds the corresponding form element, or the form element itself.
*
* @throws \LogicException If given node is not a button or input or does not have a form ancestor
*/
protected function setNode(\DOMElement $node)
{
$this->button = $node;
if ('button' === $node->nodeName || ('input' === $node->nodeName && \in_array(strtolower($node->getAttribute('type')), ['submit', 'button', 'image']))) {
if ($node->hasAttribute('form')) {
// if the node has the HTML5-compliant 'form' attribute, use it
$formId = $node->getAttribute('form');
$form = $node->ownerDocument->getElementById($formId);
if (null === $form) {
throw new \LogicException(sprintf('The selected node has an invalid form attribute (%s).', $formId));
}
$this->node = $form;
return;
}
// we loop until we find a form ancestor
do {
if (null === $node = $node->parentNode) {
throw new \LogicException('The selected node does not have a form ancestor.');
}
} while ('form' !== $node->nodeName);
} elseif ('form' !== $node->nodeName) {
throw new \LogicException(sprintf('Unable to submit on a "%s" tag.', $node->nodeName));
}
$this->node = $node;
}
/**
* Adds form elements related to this form.
*
* Creates an internal copy of the submitted 'button' element and
* the form node or the entire document depending on whether we need
* to find non-descendant elements through HTML5 'form' attribute.
*/
private function initialize()
{
$this->fields = new FormFieldRegistry();
$xpath = new \DOMXPath($this->node->ownerDocument);
// add submitted button if it has a valid name
if ('form' !== $this->button->nodeName && $this->button->hasAttribute('name') && $this->button->getAttribute('name')) {
if ('input' == $this->button->nodeName && 'image' == strtolower($this->button->getAttribute('type'))) {
$name = $this->button->getAttribute('name');
$this->button->setAttribute('value', '0');
// temporarily change the name of the input node for the x coordinate
$this->button->setAttribute('name', $name.'.x');
$this->set(new Field\InputFormField($this->button));
// temporarily change the name of the input node for the y coordinate
$this->button->setAttribute('name', $name.'.y');
$this->set(new Field\InputFormField($this->button));
// restore the original name of the input node
$this->button->setAttribute('name', $name);
} else {
$this->set(new Field\InputFormField($this->button));
}
}
// find form elements corresponding to the current form
if ($this->node->hasAttribute('id')) {
// corresponding elements are either descendants or have a matching HTML5 form attribute
$formId = Crawler::xpathLiteral($this->node->getAttribute('id'));
$fieldNodes = $xpath->query(sprintf('( descendant::input[@form=%s] | descendant::button[@form=%1$s] | descendant::textarea[@form=%1$s] | descendant::select[@form=%1$s] | //form[@id=%1$s]//input[not(@form)] | //form[@id=%1$s]//button[not(@form)] | //form[@id=%1$s]//textarea[not(@form)] | //form[@id=%1$s]//select[not(@form)] )[not(ancestor::template)]', $formId));
foreach ($fieldNodes as $node) {
$this->addField($node);
}
} else {
// do the xpath query with $this->node as the context node, to only find descendant elements
// however, descendant elements with form attribute are not part of this form
$fieldNodes = $xpath->query('( descendant::input[not(@form)] | descendant::button[not(@form)] | descendant::textarea[not(@form)] | descendant::select[not(@form)] )[not(ancestor::template)]', $this->node);
foreach ($fieldNodes as $node) {
$this->addField($node);
}
}
if ($this->baseHref && '' !== $this->node->getAttribute('action')) {
$this->currentUri = $this->baseHref;
}
}
private function addField(\DOMElement $node)
{
if (!$node->hasAttribute('name') || !$node->getAttribute('name')) {
return;
}
$nodeName = $node->nodeName;
if ('select' == $nodeName || 'input' == $nodeName && 'checkbox' == strtolower($node->getAttribute('type'))) {
$this->set(new Field\ChoiceFormField($node));
} elseif ('input' == $nodeName && 'radio' == strtolower($node->getAttribute('type'))) {
// there may be other fields with the same name that are no choice
// fields already registered (see https://github.com/symfony/symfony/issues/11689)
if ($this->has($node->getAttribute('name')) && $this->get($node->getAttribute('name')) instanceof ChoiceFormField) {
$this->get($node->getAttribute('name'))->addChoice($node);
} else {
$this->set(new Field\ChoiceFormField($node));
}
} elseif ('input' == $nodeName && 'file' == strtolower($node->getAttribute('type'))) {
$this->set(new Field\FileFormField($node));
} elseif ('input' == $nodeName && !\in_array(strtolower($node->getAttribute('type')), ['submit', 'button', 'image'])) {
$this->set(new Field\InputFormField($node));
} elseif ('textarea' == $nodeName) {
$this->set(new Field\TextareaFormField($node));
}
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/FormFieldRegistry.php | vendor/symfony/dom-crawler/FormFieldRegistry.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler;
use Symfony\Component\DomCrawler\Field\FormField;
/**
* This is an internal class that must not be used directly.
*
* @internal
*/
class FormFieldRegistry
{
private array $fields = [];
private string $base = '';
/**
* Adds a field to the registry.
*/
public function add(FormField $field)
{
$segments = $this->getSegments($field->getName());
$target = &$this->fields;
while ($segments) {
if (!\is_array($target)) {
$target = [];
}
$path = array_shift($segments);
if ('' === $path) {
$target = &$target[];
} else {
$target = &$target[$path];
}
}
$target = $field;
}
/**
* Removes a field based on the fully qualifed name and its children from the registry.
*/
public function remove(string $name)
{
$segments = $this->getSegments($name);
$target = &$this->fields;
while (\count($segments) > 1) {
$path = array_shift($segments);
if (!\is_array($target) || !\array_key_exists($path, $target)) {
return;
}
$target = &$target[$path];
}
unset($target[array_shift($segments)]);
}
/**
* Returns the value of the field based on the fully qualifed name and its children.
*
* @return FormField|FormField[]|FormField[][]
*
* @throws \InvalidArgumentException if the field does not exist
*/
public function &get(string $name): FormField|array
{
$segments = $this->getSegments($name);
$target = &$this->fields;
while ($segments) {
$path = array_shift($segments);
if (!\is_array($target) || !\array_key_exists($path, $target)) {
throw new \InvalidArgumentException(sprintf('Unreachable field "%s".', $path));
}
$target = &$target[$path];
}
return $target;
}
/**
* Tests whether the form has the given field based on the fully qualified name.
*/
public function has(string $name): bool
{
try {
$this->get($name);
return true;
} catch (\InvalidArgumentException $e) {
return false;
}
}
/**
* Set the value of a field based on the fully qualified name and its children.
*
* @throws \InvalidArgumentException if the field does not exist
*/
public function set(string $name, mixed $value)
{
$target = &$this->get($name);
if ((!\is_array($value) && $target instanceof Field\FormField) || $target instanceof Field\ChoiceFormField) {
$target->setValue($value);
} elseif (\is_array($value)) {
$registry = new static();
$registry->base = $name;
$registry->fields = $value;
foreach ($registry->all() as $k => $v) {
$this->set($k, $v);
}
} else {
throw new \InvalidArgumentException(sprintf('Cannot set value on a compound field "%s".', $name));
}
}
/**
* Returns the list of field with their value.
*
* @return FormField[] The list of fields as [string] Fully qualified name => (mixed) value)
*/
public function all(): array
{
return $this->walk($this->fields, $this->base);
}
/**
* Transforms a PHP array in a list of fully qualified name / value.
*/
private function walk(array $array, ?string $base = '', array &$output = []): array
{
foreach ($array as $k => $v) {
$path = empty($base) ? $k : sprintf('%s[%s]', $base, $k);
if (\is_array($v)) {
$this->walk($v, $path, $output);
} else {
$output[$path] = $v;
}
}
return $output;
}
/**
* Splits a field name into segments as a web browser would do.
*
* getSegments('base[foo][3][]') = ['base', 'foo, '3', ''];
*
* @return string[]
*/
private function getSegments(string $name): array
{
if (preg_match('/^(?P<base>[^[]+)(?P<extra>(\[.*)|$)/', $name, $m)) {
$segments = [$m['base']];
while (!empty($m['extra'])) {
$extra = $m['extra'];
if (preg_match('/^\[(?P<segment>.*?)\](?P<extra>.*)$/', $extra, $m)) {
$segments[] = $m['segment'];
} else {
$segments[] = $extra;
}
}
return $segments;
}
return [$name];
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Test/Constraint/CrawlerSelectorExists.php | vendor/symfony/dom-crawler/Test/Constraint/CrawlerSelectorExists.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Test\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\DomCrawler\Crawler;
final class CrawlerSelectorExists extends Constraint
{
private string $selector;
public function __construct(string $selector)
{
$this->selector = $selector;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('matches selector "%s"', $this->selector);
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function matches($crawler): bool
{
return 0 < \count($crawler->filter($this->selector));
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function failureDescription($crawler): string
{
return 'the Crawler '.$this->toString();
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Test/Constraint/CrawlerSelectorTextSame.php | vendor/symfony/dom-crawler/Test/Constraint/CrawlerSelectorTextSame.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Test\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\DomCrawler\Crawler;
final class CrawlerSelectorTextSame extends Constraint
{
private string $selector;
private string $expectedText;
public function __construct(string $selector, string $expectedText)
{
$this->selector = $selector;
$this->expectedText = $expectedText;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('has a node matching selector "%s" with content "%s"', $this->selector, $this->expectedText);
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function matches($crawler): bool
{
$crawler = $crawler->filter($this->selector);
if (!\count($crawler)) {
return false;
}
return $this->expectedText === trim($crawler->text(null, true));
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function failureDescription($crawler): string
{
return 'the Crawler '.$this->toString();
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Test/Constraint/CrawlerSelectorAttributeValueSame.php | vendor/symfony/dom-crawler/Test/Constraint/CrawlerSelectorAttributeValueSame.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Test\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\DomCrawler\Crawler;
final class CrawlerSelectorAttributeValueSame extends Constraint
{
private string $selector;
private string $attribute;
private string $expectedText;
public function __construct(string $selector, string $attribute, string $expectedText)
{
$this->selector = $selector;
$this->attribute = $attribute;
$this->expectedText = $expectedText;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('has a node matching selector "%s" with attribute "%s" of value "%s"', $this->selector, $this->attribute, $this->expectedText);
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function matches($crawler): bool
{
$crawler = $crawler->filter($this->selector);
if (!\count($crawler)) {
return false;
}
return $this->expectedText === trim($crawler->attr($this->attribute) ?? '');
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function failureDescription($crawler): string
{
return 'the Crawler '.$this->toString();
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Test/Constraint/CrawlerSelectorTextContains.php | vendor/symfony/dom-crawler/Test/Constraint/CrawlerSelectorTextContains.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Test\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\DomCrawler\Crawler;
final class CrawlerSelectorTextContains extends Constraint
{
private string $selector;
private string $expectedText;
private bool $hasNode = false;
private string $nodeText;
public function __construct(string $selector, string $expectedText)
{
$this->selector = $selector;
$this->expectedText = $expectedText;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
if ($this->hasNode) {
return sprintf('the text "%s" of the node matching selector "%s" contains "%s"', $this->nodeText, $this->selector, $this->expectedText);
}
return sprintf('the Crawler has a node matching selector "%s"', $this->selector);
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function matches($crawler): bool
{
$crawler = $crawler->filter($this->selector);
if (!\count($crawler)) {
$this->hasNode = false;
return false;
}
$this->hasNode = true;
$this->nodeText = $crawler->text(null, true);
return false !== mb_strpos($this->nodeText, $this->expectedText);
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function failureDescription($crawler): string
{
return $this->toString();
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Field/FormField.php | vendor/symfony/dom-crawler/Field/FormField.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Field;
/**
* FormField is the abstract class for all form fields.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class FormField
{
/**
* @var \DOMElement
*/
protected $node;
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $value;
/**
* @var \DOMDocument
*/
protected $document;
/**
* @var \DOMXPath
*/
protected $xpath;
/**
* @var bool
*/
protected $disabled;
/**
* @param \DOMElement $node The node associated with this field
*/
public function __construct(\DOMElement $node)
{
$this->node = $node;
$this->name = $node->getAttribute('name');
$this->xpath = new \DOMXPath($node->ownerDocument);
$this->initialize();
}
/**
* Returns the label tag associated to the field or null if none.
*/
public function getLabel(): ?\DOMElement
{
$xpath = new \DOMXPath($this->node->ownerDocument);
if ($this->node->hasAttribute('id')) {
$labels = $xpath->query(sprintf('descendant::label[@for="%s"]', $this->node->getAttribute('id')));
if ($labels->length > 0) {
return $labels->item(0);
}
}
$labels = $xpath->query('ancestor::label[1]', $this->node);
return $labels->length > 0 ? $labels->item(0) : null;
}
/**
* Returns the name of the field.
*/
public function getName(): string
{
return $this->name;
}
/**
* Gets the value of the field.
*/
public function getValue(): string|array|null
{
return $this->value;
}
/**
* Sets the value of the field.
*/
public function setValue(?string $value)
{
$this->value = $value ?? '';
}
/**
* Returns true if the field should be included in the submitted values.
*/
public function hasValue(): bool
{
return true;
}
/**
* Check if the current field is disabled.
*/
public function isDisabled(): bool
{
return $this->node->hasAttribute('disabled');
}
/**
* Initializes the form field.
*/
abstract protected function initialize();
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Field/FileFormField.php | vendor/symfony/dom-crawler/Field/FileFormField.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Field;
/**
* FileFormField represents a file form field (an HTML file input tag).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class FileFormField extends FormField
{
/**
* Sets the PHP error code associated with the field.
*
* @param int $error The error code (one of UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, or UPLOAD_ERR_EXTENSION)
*
* @throws \InvalidArgumentException When error code doesn't exist
*/
public function setErrorCode(int $error)
{
$codes = [\UPLOAD_ERR_INI_SIZE, \UPLOAD_ERR_FORM_SIZE, \UPLOAD_ERR_PARTIAL, \UPLOAD_ERR_NO_FILE, \UPLOAD_ERR_NO_TMP_DIR, \UPLOAD_ERR_CANT_WRITE, \UPLOAD_ERR_EXTENSION];
if (!\in_array($error, $codes)) {
throw new \InvalidArgumentException(sprintf('The error code "%s" is not valid.', $error));
}
$this->value = ['name' => '', 'type' => '', 'tmp_name' => '', 'error' => $error, 'size' => 0];
}
/**
* Sets the value of the field.
*/
public function upload(?string $value)
{
$this->setValue($value);
}
/**
* Sets the value of the field.
*/
public function setValue(?string $value)
{
if (null !== $value && is_readable($value)) {
$error = \UPLOAD_ERR_OK;
$size = filesize($value);
$info = pathinfo($value);
$name = $info['basename'];
// copy to a tmp location
$tmp = sys_get_temp_dir().'/'.strtr(substr(base64_encode(hash('sha256', uniqid(mt_rand(), true), true)), 0, 7), '/', '_');
if (\array_key_exists('extension', $info)) {
$tmp .= '.'.$info['extension'];
}
if (is_file($tmp)) {
unlink($tmp);
}
copy($value, $tmp);
$value = $tmp;
} else {
$error = \UPLOAD_ERR_NO_FILE;
$size = 0;
$name = '';
$value = '';
}
$this->value = ['name' => $name, 'type' => '', 'tmp_name' => $value, 'error' => $error, 'size' => $size];
}
/**
* Sets path to the file as string for simulating HTTP request.
*/
public function setFilePath(string $path)
{
parent::setValue($path);
}
/**
* Initializes the form field.
*
* @throws \LogicException When node type is incorrect
*/
protected function initialize()
{
if ('input' !== $this->node->nodeName) {
throw new \LogicException(sprintf('A FileFormField can only be created from an input tag (%s given).', $this->node->nodeName));
}
if ('file' !== strtolower($this->node->getAttribute('type'))) {
throw new \LogicException(sprintf('A FileFormField can only be created from an input tag with a type of file (given type is "%s").', $this->node->getAttribute('type')));
}
$this->setValue(null);
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Field/ChoiceFormField.php | vendor/symfony/dom-crawler/Field/ChoiceFormField.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Field;
/**
* ChoiceFormField represents a choice form field.
*
* It is constructed from an HTML select tag, or an HTML checkbox, or radio inputs.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ChoiceFormField extends FormField
{
private string $type;
private bool $multiple;
private array $options;
private bool $validationDisabled = false;
/**
* Returns true if the field should be included in the submitted values.
*
* @return bool true if the field should be included in the submitted values, false otherwise
*/
public function hasValue(): bool
{
// don't send a value for unchecked checkboxes
if (\in_array($this->type, ['checkbox', 'radio']) && null === $this->value) {
return false;
}
return true;
}
/**
* Check if the current selected option is disabled.
*/
public function isDisabled(): bool
{
if (parent::isDisabled() && 'select' === $this->type) {
return true;
}
foreach ($this->options as $option) {
if ($option['value'] == $this->value && $option['disabled']) {
return true;
}
}
return false;
}
/**
* Sets the value of the field.
*/
public function select(string|array|bool $value)
{
$this->setValue($value);
}
/**
* Ticks a checkbox.
*
* @throws \LogicException When the type provided is not correct
*/
public function tick()
{
if ('checkbox' !== $this->type) {
throw new \LogicException(sprintf('You cannot tick "%s" as it is not a checkbox (%s).', $this->name, $this->type));
}
$this->setValue(true);
}
/**
* Unticks a checkbox.
*
* @throws \LogicException When the type provided is not correct
*/
public function untick()
{
if ('checkbox' !== $this->type) {
throw new \LogicException(sprintf('You cannot untick "%s" as it is not a checkbox (%s).', $this->name, $this->type));
}
$this->setValue(false);
}
/**
* Sets the value of the field.
*
* @throws \InvalidArgumentException When value type provided is not correct
*/
public function setValue(string|array|bool|null $value)
{
if ('checkbox' === $this->type && false === $value) {
// uncheck
$this->value = null;
} elseif ('checkbox' === $this->type && true === $value) {
// check
$this->value = $this->options[0]['value'];
} else {
if (\is_array($value)) {
if (!$this->multiple) {
throw new \InvalidArgumentException(sprintf('The value for "%s" cannot be an array.', $this->name));
}
foreach ($value as $v) {
if (!$this->containsOption($v, $this->options)) {
throw new \InvalidArgumentException(sprintf('Input "%s" cannot take "%s" as a value (possible values: "%s").', $this->name, $v, implode('", "', $this->availableOptionValues())));
}
}
} elseif (!$this->containsOption($value, $this->options)) {
throw new \InvalidArgumentException(sprintf('Input "%s" cannot take "%s" as a value (possible values: "%s").', $this->name, $value, implode('", "', $this->availableOptionValues())));
}
if ($this->multiple) {
$value = (array) $value;
}
if (\is_array($value)) {
$this->value = $value;
} else {
parent::setValue($value);
}
}
}
/**
* Adds a choice to the current ones.
*
* @throws \LogicException When choice provided is not multiple nor radio
*
* @internal
*/
public function addChoice(\DOMElement $node)
{
if (!$this->multiple && 'radio' !== $this->type) {
throw new \LogicException(sprintf('Unable to add a choice for "%s" as it is not multiple or is not a radio button.', $this->name));
}
$option = $this->buildOptionValue($node);
$this->options[] = $option;
if ($node->hasAttribute('checked')) {
$this->value = $option['value'];
}
}
/**
* Returns the type of the choice field (radio, select, or checkbox).
*/
public function getType(): string
{
return $this->type;
}
/**
* Returns true if the field accepts multiple values.
*/
public function isMultiple(): bool
{
return $this->multiple;
}
/**
* Initializes the form field.
*
* @throws \LogicException When node type is incorrect
*/
protected function initialize()
{
if ('input' !== $this->node->nodeName && 'select' !== $this->node->nodeName) {
throw new \LogicException(sprintf('A ChoiceFormField can only be created from an input or select tag (%s given).', $this->node->nodeName));
}
if ('input' === $this->node->nodeName && 'checkbox' !== strtolower($this->node->getAttribute('type')) && 'radio' !== strtolower($this->node->getAttribute('type'))) {
throw new \LogicException(sprintf('A ChoiceFormField can only be created from an input tag with a type of checkbox or radio (given type is "%s").', $this->node->getAttribute('type')));
}
$this->value = null;
$this->options = [];
$this->multiple = false;
if ('input' == $this->node->nodeName) {
$this->type = strtolower($this->node->getAttribute('type'));
$optionValue = $this->buildOptionValue($this->node);
$this->options[] = $optionValue;
if ($this->node->hasAttribute('checked')) {
$this->value = $optionValue['value'];
}
} else {
$this->type = 'select';
if ($this->node->hasAttribute('multiple')) {
$this->multiple = true;
$this->value = [];
$this->name = str_replace('[]', '', $this->name);
}
$found = false;
foreach ($this->xpath->query('descendant::option', $this->node) as $option) {
$optionValue = $this->buildOptionValue($option);
$this->options[] = $optionValue;
if ($option->hasAttribute('selected')) {
$found = true;
if ($this->multiple) {
$this->value[] = $optionValue['value'];
} else {
$this->value = $optionValue['value'];
}
}
}
// if no option is selected and if it is a simple select box, take the first option as the value
if (!$found && !$this->multiple && !empty($this->options)) {
$this->value = $this->options[0]['value'];
}
}
}
/**
* Returns option value with associated disabled flag.
*/
private function buildOptionValue(\DOMElement $node): array
{
$option = [];
$defaultDefaultValue = 'select' === $this->node->nodeName ? '' : 'on';
$defaultValue = (isset($node->nodeValue) && !empty($node->nodeValue)) ? $node->nodeValue : $defaultDefaultValue;
$option['value'] = $node->hasAttribute('value') ? $node->getAttribute('value') : $defaultValue;
$option['disabled'] = $node->hasAttribute('disabled');
return $option;
}
/**
* Checks whether given value is in the existing options.
*
* @internal
*/
public function containsOption(string $optionValue, array $options): bool
{
if ($this->validationDisabled) {
return true;
}
foreach ($options as $option) {
if ($option['value'] == $optionValue) {
return true;
}
}
return false;
}
/**
* Returns list of available field options.
*
* @internal
*/
public function availableOptionValues(): array
{
$values = [];
foreach ($this->options as $option) {
$values[] = $option['value'];
}
return $values;
}
/**
* Disables the internal validation of the field.
*
* @internal
*
* @return $this
*/
public function disableValidation(): static
{
$this->validationDisabled = true;
return $this;
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Field/InputFormField.php | vendor/symfony/dom-crawler/Field/InputFormField.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Field;
/**
* InputFormField represents an input form field (an HTML input tag).
*
* For inputs with type of file, checkbox, or radio, there are other more
* specialized classes (cf. FileFormField and ChoiceFormField).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class InputFormField extends FormField
{
/**
* Initializes the form field.
*
* @throws \LogicException When node type is incorrect
*/
protected function initialize()
{
if ('input' !== $this->node->nodeName && 'button' !== $this->node->nodeName) {
throw new \LogicException(sprintf('An InputFormField can only be created from an input or button tag (%s given).', $this->node->nodeName));
}
$type = strtolower($this->node->getAttribute('type'));
if ('checkbox' === $type) {
throw new \LogicException('Checkboxes should be instances of ChoiceFormField.');
}
if ('file' === $type) {
throw new \LogicException('File inputs should be instances of FileFormField.');
}
$this->value = $this->node->getAttribute('value');
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
kiang/pharmacies | https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/symfony/dom-crawler/Field/TextareaFormField.php | vendor/symfony/dom-crawler/Field/TextareaFormField.php | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Field;
/**
* TextareaFormField represents a textarea form field (an HTML textarea tag).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TextareaFormField extends FormField
{
/**
* Initializes the form field.
*
* @throws \LogicException When node type is incorrect
*/
protected function initialize()
{
if ('textarea' !== $this->node->nodeName) {
throw new \LogicException(sprintf('A TextareaFormField can only be created from a textarea tag (%s given).', $this->node->nodeName));
}
$this->value = '';
foreach ($this->node->childNodes as $node) {
$this->value .= $node->wholeText;
}
}
}
| php | MIT | 0c425bab53cc1db30b2adadc50fb2ea112d5f414 | 2026-01-05T03:37:52.991734Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.