Skip to content

Commit 541e402

Browse files
authored
correct logic for async fetching content types (#26)
1 parent 1d41bf2 commit 541e402

File tree

1 file changed

+30
-17
lines changed

1 file changed

+30
-17
lines changed

src/Contentful.php

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -219,12 +219,18 @@ public function getContentType($id, $space = null, array $options = [])
219219
}
220220

221221
//fetch them all and pick one out, as it is likely we'll want to access others
222-
$contentTypes = $this->getContentTypes([], $space, $options);
223-
foreach ($contentTypes as $contentType) {
224-
$this->envelope->insertContentType($contentType);
225-
}
222+
$contentTypesPromise = promise_for($this->getContentTypes([], $space, $options))
223+
->then(
224+
function ($contentTypes) use ($id) {
225+
foreach ($contentTypes as $contentType) {
226+
$this->envelope->insertContentType($contentType);
227+
}
228+
229+
return promise_for($this->envelope->findContentType($id));
230+
}
231+
);
226232

227-
return $this->envelope->findContentType($id);
233+
return (isset($options['async']) && $options['async']) ? $contentTypesPromise : $contentTypesPromise->wait();
228234
}
229235

230236
/**
@@ -262,20 +268,27 @@ public function getContentTypes(array $parameters = [], $space = null, array $op
262268
*/
263269
public function getContentTypeByName($name, $space = null, array $options = [])
264270
{
265-
$contentTypeFromEnvelope = $this->envelope->findContentTypeByName($name);
266-
if ($contentTypeFromEnvelope) {
267-
return $contentTypeFromEnvelope;
268-
}
269-
$contentTypes = $this->getContentTypes([], $space, $options);
270-
$foundContentType = null;
271-
foreach ($contentTypes as $contentType) {
272-
if ($contentType->getName() === $name) {
273-
$foundContentType = $contentType;
271+
$promise = coroutine(
272+
function () use ($name, $space, $options) {
273+
$contentTypeFromEnvelope = $this->envelope->findContentTypeByName($name);
274+
if ($contentTypeFromEnvelope) {
275+
yield promise_for($contentTypeFromEnvelope);
276+
return;
277+
}
278+
$contentTypes = (yield $this->getContentTypes([], $space, array_merge($options, ['async' => true])));
279+
$foundContentType = null;
280+
foreach ($contentTypes as $contentType) {
281+
if ($contentType->getName() === $name) {
282+
$foundContentType = $contentType;
283+
}
284+
$this->envelope->insertContentType($contentType);
285+
}
286+
287+
yield $foundContentType;
274288
}
275-
$this->envelope->insertContentType($contentType);
276-
}
289+
);
277290

278-
return $foundContentType;
291+
return (isset($options['async']) && $options['async']) ? $promise : $promise->wait();
279292
}
280293

281294
/**

0 commit comments

Comments
 (0)