Skip to content

Commit

Permalink
Merge branch 'master' of github.com:luyadev/luya-headless
Browse files Browse the repository at this point in the history
  • Loading branch information
nadar committed Jul 13, 2020
2 parents 0b7caa8 + 2857540 commit fb65b19
Show file tree
Hide file tree
Showing 9 changed files with 165 additions and 16 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file.

This project adheres to [Semantic Versioning](http://semver.org/).

## 2.6.0

+ [#29](https://github.com/luyadev/luya-headless/pull/29) Refactoring of the caching system. The CURL collection class serializes the response into a json and stores this information in the cache. The previous version stored the full PHP class object which might lead into errors when working with memcached servers.

## 2.5.0 (3. March 2020)

+ [#27](https://github.com/luyadev/luya-headless/issues/27) New sort() method for BaseIterator objects.
Expand Down
6 changes: 3 additions & 3 deletions src/base/AbstractEndpointRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ public function response(Client $client)

if ($this->getCache() !== false) {
$cacheKey = $this->_cacheIdentifier ? $this->_cacheIdentifier : Client::cacheKey([$client->cachePrefix, $this->getEndpoint(), $this->_args, $client->language]);
return $requestClient->getOrSetCache($cacheKey, $client->applyCacheTimeAnomaly($this->getCache()), function () use ($requestClient) {
return $this->createResponse($requestClient);
});

// set the information to the request client that caching is enabled for the given ttl with this key
$requestClient->enableCaching($cacheKey, $client->applyCacheTimeAnomaly($this->getCache()));
}

return $this->createResponse($requestClient);
Expand Down
80 changes: 74 additions & 6 deletions src/base/AbstractRequestClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ protected function callBeforeRequestEvent(array $data, $type)
protected function callAfterRequestEvent(array $data, $type)
{
if ($this->client->getAfterRequestEvent()) {
call_user_func_array($this->client->getAfterRequestEvent(), [new AfterRequestEvent($this->getRequestUrl(), $data, $this->getResponseStatusCode(), $this->getResponseRawContent(), $type)]);
call_user_func_array($this->client->getAfterRequestEvent(), [new AfterRequestEvent($this->getRequestUrl(), $data, $this->getResponseStatusCode(), $this->getResponseRawContent(), $type, $this)]);
}
}

Expand Down Expand Up @@ -302,6 +302,76 @@ public function responseStatusCodeExceptionCheck($statusCode)
throw new RequestException(sprintf('Unable to find API "%s". Invalid endpoint name or serverUrl.', $this->getRequestUrl()));
}
}

private $_cacheConfig = false;

/**
* Enable caching for this request with a given key and ttl.
*
* @param string $key
* @param initeger $ttl
* @since 2.6.0
*/
public function enableCaching($key, $ttl)
{
$this->_cacheConfig = [$key, $ttl];
}

/**
* Returns the key for the caching.
*
* @return string|boolean If caching is enabled, the key which will be used to cache will be returned.
* @since 2.6.0
*/
public function getCacheKey()
{
return $this->isCachingEnabled() ? $this->_cacheConfig[0] : false;
}

/**
* Returns the time to life for the caching.
*
* @return integer|boolean If caching is enabled, the TTL value is returned.
* @since 2.6.0
*/
public function getCacheTtl()
{
return $this->isCachingEnabled() ? $this->_cacheConfig[1] : false;
}

/**
* Determines whether the current request can be cached or not
*
* @return boolean
* @since 2.6.0
*/
public function isCachingEnabled()
{
return $this->_cacheConfig !== false;
}

private $_isCached = false;

/**
* Returns the status whether the current request has been cached or not
*
* @return integer
* @since 2.6.0
*/
public function getIsCached()
{
return $this->_isCached;
}

/**
* Set the status of this request as cached.
*
* @since 2.6.0
*/
public function setIsCached()
{
$this->_isCached = true;
}

/**
* Get an existing key, or set a new value for the given cache key.
Expand All @@ -322,16 +392,14 @@ public function getOrSetCache($key, $ttl, callable $fn)
$content = $cache->get($key, false);

if ($content !== false) {
$this->setIsCached();
return $content;
}

$content = call_user_func($fn);

// only cache the response if the request was successfull
if ($this->isSuccess()) {
if (!$cache->set($key, $content, $ttl)) {
throw new Exception("Unable to store the cache content for key '{$key}'.");
}
if (!$cache->set($key, $content, $ttl)) {
throw new Exception("Unable to store the cache content for key '{$key}'.");
}

return $content;
Expand Down
19 changes: 18 additions & 1 deletion src/base/AfterRequestEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,29 @@ class AfterRequestEvent
public $content;
public $type;

public function __construct($url, array $data, $statusCode, $content, $type)
/**
* @var AbstractRequestClient
* @since 2.6.0
*/
public $requestClient;

/**
* Constructor
*
* @param string $url
* @param array $data
* @param integer $statusCode
* @param mixed $content
* @param string $type
* @param AbstractRequestClient $requestClient
*/
public function __construct($url, array $data, $statusCode, $content, $type, AbstractRequestClient $requestClient)
{
$this->url = $url;
$this->data = $data;
$this->statusCode = $statusCode;
$this->content = $content;
$this->type = $type;
$this->requestClient = $requestClient;
}
}
7 changes: 7 additions & 0 deletions src/base/BeforeRequestEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ class BeforeRequestEvent
public $data;
public $type;

/**
* Constructor
*
* @param string $url
* @param array $data
* @param string $type
*/
public function __construct($url, array $data, $type)
{
$this->url = $url;
Expand Down
23 changes: 21 additions & 2 deletions src/collectors/CurlRequestClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,27 @@ private function getCurl()
*/
public function internalGet()
{
$this->curl = $this->getCurl()->get($this->getRequestUrl());

if ($this->isCachingEnabled()) {
$json = $this->getOrSetCache($this->getCacheKey(), $this->getCacheTtl(), function() {
$curl = $this->getCurl()->get($this->getRequestUrl());
return json_encode([
'http_status_code' => $curl->http_status_code,
'request_headers' => $curl->request_headers,
'response_headers' => $curl->response_headers,
'response' => $curl->response
]);
});

$jsonArray = json_decode($json, true);

$this->curl = new Curl;
$this->curl->http_status_code = $jsonArray['http_status_code'];
$this->curl->request_headers = $jsonArray['request_headers'];
$this->curl->response_headers = $jsonArray['response_headers'];
$this->curl->response = $jsonArray['response'];
} else {
$this->curl = $this->getCurl()->get($this->getRequestUrl());
}
return $this;
}

Expand Down
9 changes: 7 additions & 2 deletions tests/base/AbstractActiveEndpointCachingFailuresTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace luya\headless\tests\base;

use luya\headless\Client;
use luya\headless\Exception;
use luya\headless\tests\HeadlessTestCase;
use luya\headless\tests\data\DummySimpleCache;

Expand All @@ -19,8 +21,11 @@ public function getClient()

public function testFindTokenWithCacheWhichIsDisabled()
{
$client = $this->createDummyClient('{"id":1}');
$this->expectException('luya\headless\Exception');
$client = new Client(null, 'https://jsonplaceholder.typicode.com');
$cache = new DummySimpleCache();
$cache->setReturn = false;
$client->setCache($cache);
$this->expectException(Exception::class);
$data = TestActiveEndpoint::testTokenUrl(123)->setCache(3600)->response($client);
$this->assertSame(['id' => 1], $data->getContent());
}
Expand Down
32 changes: 31 additions & 1 deletion tests/base/AbstractActiveEndpointCachingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use luya\headless\tests\HeadlessTestCase;
use luya\headless\tests\data\DummySimpleCache;
use luya\headless\cache\DynamicValue;
use luya\headless\Client;
use luya\headless\Endpoint;

class AbstractActiveEndpointCachingTest extends HeadlessTestCase
{
Expand Down Expand Up @@ -71,4 +73,32 @@ public function testCacheWithDynamicValue()
['foo', 'foo' => new DynamicValue(123), 'sub' => [new DynamicValue('1234')]]
]));
}
}

public function testRequestWithDummyCachingEnabled()
{
$client = new Client(null, 'https://jsonplaceholder.typicode.com');
$client->setCache(new DummySimpleCache());

$class = new class() extends Endpoint {
public function getEndpointName()
{
return 'todos/1';
}
};

$run1 = $class->get()->setCache(30)->response($client);

$this->assertSame([
'userId' => 1,
'id' => 1,
'title' => 'delectus aut autem',
'completed' => false,
], $run1->getContent());

$this->assertFalse($run1->requestClient->getIsCached());

$run2 = $class->get()->setCache(30)->response($client);

$this->assertTrue($run2->requestClient->getIsCached());
}
}
1 change: 0 additions & 1 deletion tests/base/AbstractActiveEndpointTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use luya\headless\tests\HeadlessTestCase;
use luya\headless\ActiveEndpoint;
use luya\headless\cache\DynamicValue;

final class TestActiveEndpoint extends ActiveEndpoint
{
Expand Down

0 comments on commit fb65b19

Please sign in to comment.