Skip to content

Commit

Permalink
Merge branch 'master' into 4.2
Browse files Browse the repository at this point in the history
# Conflicts:
#	packages/dom/src/HTMLElement.php
#	packages/http/test/Transport/AbstractTransportTestCase.php
  • Loading branch information
asika32764 committed Dec 10, 2024
2 parents a420142 + aa150fd commit d3bf3a0
Show file tree
Hide file tree
Showing 10 changed files with 141 additions and 76 deletions.
14 changes: 9 additions & 5 deletions packages/cache/src/CachePool.php
Original file line number Diff line number Diff line change
Expand Up @@ -324,17 +324,21 @@ public function has($key): bool
*
* @throws \Psr\Cache\InvalidArgumentException
*/
public function call(string $key, callable $handler, DateInterval|int|null $ttl = null): mixed
public function call(string $key, callable $handler, DateInterval|int|null $ttl = null, bool $lock = false): mixed
{
$storage = $this->storage;
$isHit = null;

if ($storage instanceof LockableStorageInterface) {
$storage->lock($key);
if ($lock && $storage instanceof LockableStorageInterface) {
$storage->lock($key, $isNew);
$isHit = !$isNew;
}

$item = $this->getItem($key);

if ($item->isHit()) {
$isHit ??= $item->isHit();

if ($isHit) {
return $this->serializer->unserialize($item->get());
}

Expand All @@ -343,7 +347,7 @@ public function call(string $key, callable $handler, DateInterval|int|null $ttl

$this->save($item);

if ($storage instanceof LockableStorageInterface) {
if ($lock && $storage instanceof LockableStorageInterface) {
$storage->release($key);
}

Expand Down
16 changes: 14 additions & 2 deletions packages/cache/src/Storage/FileStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,12 @@ protected function write(string $key, string $value): bool
{
$filename = $this->fetchStreamUri($key);

if ($this->isLocked($key)) {
$fp = $this->lockedResources[$filename];

return (bool) fwrite($fp, $value);
}

return (bool) file_put_contents(
$filename,
$value,
Expand Down Expand Up @@ -356,19 +362,25 @@ protected function getExpirationFormat(): string
return (string) $this->getOption('expiration_format');
}

public function lock(string $key): bool
public function lock(string $key, ?bool &$isNew = null): bool
{
if (!$this->shouldLock()) {
$isNew = false;

return true;
}

if ($this->isLocked($key)) {
$isNew = false;

return true;
}

$filePath = $this->fetchStreamUri($key);

$this->lockedResources[$filePath] = fopen($filePath, 'rb');
$isNew = !file_exists($filePath);

$this->lockedResources[$filePath] = fopen($filePath, 'cb+');

return flock($this->lockedResources[$filePath], LOCK_EX);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cache/src/Storage/LockableStorageInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

interface LockableStorageInterface
{
public function lock(string $key): bool;
public function lock(string $key, ?bool &$isNew = null): bool;

public function release(string $key): bool;

Expand Down
4 changes: 2 additions & 2 deletions packages/dom/src/HTMLElement.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ class HTMLElement extends NativeHTMLElement implements \ArrayAccess
*
* @return DOMElement
*
* @deprecated Use new() instead.
* @deprecated Use HTMLElement::new() instead.
*/
#[\Deprecated(message: 'Use HTMLDomFactory::element() instead.')]
#[\Deprecated(message: 'Use HTMLElement::new() instead.')]
public static function create(string $name, array $attributes = [], mixed $content = null): DOMElement
{
return DOMElement::create($name, $attributes, $content)->asHTML();
Expand Down
17 changes: 16 additions & 1 deletion packages/http/src/HttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ public function download(
mixed $body = null,
array $options = []
): HttpClientResponse {
$options = Arr::mergeRecursive($this->getOptions(), $options);

if ($url instanceof RequestInterface) {
$request = $this->hydrateRequest(
Expand Down Expand Up @@ -145,6 +146,16 @@ public function sendRequest(RequestInterface $request, array $options = []): Htt
throw new RangeException(get_class($transport) . ' driver not supported.');
}

if (!($options['option_merged'] ?? false)) {
$options = Arr::mergeRecursive(
$this->getOptions()['transport'] ?? [],
[
'files' => $this->getOptions()['files'] ?? null,
],
$options,
);
}

return $transport->request($request, $options);
}

Expand Down Expand Up @@ -204,7 +215,7 @@ public function get(Stringable|string $url, array $options = []): HttpClientResp
*
* @since 2.1
*/
public function post(Stringable|string $url, mixed $body, array $options = []): HttpClientResponse
public function post(Stringable|string $url, mixed $body = null, array $options = []): HttpClientResponse
{
return $this->request('POST', $url, $body, $options);
}
Expand Down Expand Up @@ -415,11 +426,15 @@ public function request(
mixed $body = null,
array $options = []
): HttpClientResponse {
$options = Arr::mergeRecursive($this->getOptions(), $options);

$request = $this->hydrateRequest(new Request(), $method, $url, $body, $options);

$transportOptions = $options['transport'] ?? [];
$transportOptions['files'] = $options['files'] ?? null;

$transportOptions['option_merged'] = true;

$response = $this->sendRequest($request, $transportOptions);

$httpClient = $this;
Expand Down
7 changes: 5 additions & 2 deletions packages/http/src/Transport/CurlTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public function prepareRequestOptions(array $options): array
[
'ignore_curl_error' => false,
'allow_empty_status_code' => false,
'auto_calc_content_length' => true,
'write_stream' => 'php://memory',
'timeout' => null,
'user_agent' => null,
Expand Down Expand Up @@ -305,7 +306,9 @@ protected function prepareCurlOptions(RequestInterface $request, array $options)
$request = static::prepareHeaders($request, $forceMultipart);

// Add the relevant headers.
if (isset($opt[CURLOPT_POSTFIELDS]) && $opt[CURLOPT_POSTFIELDS] !== '') {
$calcLength = (bool) ($options['auto_calc_content_length'] ?? true);

if ($calcLength && isset($opt[CURLOPT_POSTFIELDS]) && $opt[CURLOPT_POSTFIELDS] !== '') {
$request = $request->withHeader('Content-Length', (string) strlen($opt[CURLOPT_POSTFIELDS]));
}

Expand Down Expand Up @@ -333,7 +336,7 @@ protected function prepareCurlOptions(RequestInterface $request, array $options)
$opt[CURLOPT_RETURNTRANSFER] = true;

// Override the Expect header to prevent cURL from confusing itself in its own stupidity.
// Link: http://the-stickman.com/web-development/php-and-curl-disabling-100-continue-header/
// @see https://stackoverflow.com/questions/14158675/how-can-i-stop-curl-from-using-100-continue
$opt[CURLOPT_HTTPHEADER][] = 'Expect:';

/*
Expand Down
76 changes: 47 additions & 29 deletions packages/http/test/HttpClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Windwalker\Http\Response\HttpClientResponse;
use Windwalker\Http\Response\JsonResponse;
use Windwalker\Http\Test\Mock\MockTransport;
use Windwalker\Http\Test\Transport\TestServerExistsTrait;
use Windwalker\Http\Transport\CurlTransport;
use Windwalker\Promise\Promise;
use Windwalker\Test\Traits\BaseAssertionTrait;
Expand All @@ -30,6 +31,7 @@
class HttpClientTest extends TestCase
{
use BaseAssertionTrait;
use TestServerExistsTrait;

/**
* Test instance.
Expand Down Expand Up @@ -376,9 +378,7 @@ public function testPatch()

public function testGetAsync(): void
{
if (!defined('WINDWALKER_TEST_HTTP_URL')) {
static::markTestSkipped('No WINDWALKER_TEST_HTTP_URL provided');
}
self::checkTestServerRunningOrSkip();

$http = new HttpClient(['base_uri' => Str::ensureRight(WINDWALKER_TEST_HTTP_URL, '/')]);

Expand Down Expand Up @@ -525,35 +525,53 @@ public function testCurlCmd(): void
);
}

/**
* Method to test getTransport().
*
* @return void
*
* @covers \Windwalker\Http\HttpClient::getTransport
* @TODO Implement testGetTransport().
*/
public function testGetTransport()
public function testOptionsMerged(): void
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
$http = new HttpClient(
[
'transport' => [
'root' => true
]
],
$transport = new MockTransport()
);
}

/**
* Method to test setTransport().
*
* @return void
*
* @covers \Windwalker\Http\HttpClient::setTransport
* @TODO Implement testSetTransport().
*/
public function testSetTransport()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
$http->get('.', ['transport' => ['foo' => 'bar']]);

self::assertEquals(
[
'root' => true,
'files' => null,
'foo' => 'bar',
'option_merged' => true,
],
$transport->receivedOptions
);

$http->request('GET', '.', null, ['transport' => ['foo' => 'bar']]);

self::assertEquals(
[
'root' => true,
'files' => null,
'foo' => 'bar',
'option_merged' => true,
],
$transport->receivedOptions
);

$http->sendRequest(
new Request(),
['foo' => 'bar']
);

self::assertEquals(
[
'root' => true,
'files' => null,
'foo' => 'bar',
],
$transport->receivedOptions
);
}
}
11 changes: 5 additions & 6 deletions packages/http/test/Mock/MockTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,9 @@
*/
class MockTransport extends AbstractTransport
{
/**
* Property request.
*
* @var RequestInterface
*/
public $request;
public RequestInterface $request;

public array $receivedOptions = [];

/**
* Send a request to the server and return a Response object with the response.
Expand All @@ -40,6 +37,8 @@ public function request(RequestInterface $request, array $options = []): HttpCli
{
$this->request = $request;

$this->receivedOptions = $options;

return $this->doRequest($request, $options);
}

Expand Down
32 changes: 4 additions & 28 deletions packages/http/test/Transport/AbstractTransportTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\StreamInterface;
use RuntimeException;
use Windwalker\Http\Exception\HttpRequestException;
use Windwalker\Http\Request\Request;
use Windwalker\Http\Transport\AbstractTransport;
use Windwalker\Stream\Stream;
Expand All @@ -25,6 +24,7 @@
abstract class AbstractTransportTestCase extends TestCase
{
use BaseAssertionTrait;
use TestServerExistsTrait;

/**
* Property options.
Expand All @@ -49,9 +49,7 @@ abstract class AbstractTransportTestCase extends TestCase
*/
public static function setUpBeforeClass(): void
{
if (!defined('WINDWALKER_TEST_HTTP_URL')) {
static::markTestSkipped('No WINDWALKER_TEST_HTTP_URL provided');
}
self::checkTestServerRunningOrSkip();
}

/**
Expand Down Expand Up @@ -300,38 +298,16 @@ public function testWriteStream(): void
);
}

protected function getTestUrl(): Uri
protected static function getTestUrl(): Uri
{
return new Uri(static::getTestUrlFromConstant());
}

protected function getHost(): string
{
return $this->getTestUrl()->toString(Uri::HOST | Uri::PORT);
return static::getTestUrl()->toString(Uri::HOST | Uri::PORT);
}

/**
* @inheritDoc
*/
// protected function runTest(): mixed
// {
// try {
// return parent::runTest();
// } catch (HttpRequestException $e) {
// if (str_contains($e->getMessage(), 'Connection refused')) {
// throw new HttpRequestException(
// $e->getMessage() . ' - Try run: ' . sprintf(
// 'php -S %s:%s bin/test-server.php',
// $this->getTestUrl()->getHost(),
// $this->getTestUrl()->getPort()
// )
// );
// }
//
// throw $e;
// }
// }

/**
* @return mixed
*/
Expand Down
Loading

0 comments on commit d3bf3a0

Please sign in to comment.