Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions dialogflow/src/detect_intent_stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,18 +78,23 @@ function detect_intent_stream($projectId, $path, $sessionId, $languageCode = 'en
foreach ($requests as $request) {
$stream->write($request);
}

// The query result is not always on the last response. When output audio is
// requested the server keeps streaming audio after it, so keep the last one
// we see instead of only looking at the final response.
$queryResult = null;
foreach ($stream->closeWriteAndReadAll() as $response) {
$recognitionResult = $response->getRecognitionResult();
if ($recognitionResult) {
$transcript = $recognitionResult->getTranscript();
printf('Intermediate transcript: %s' . PHP_EOL, $transcript);
}
$queryResult = $response->getQueryResult() ?: $queryResult;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using the Elvis operator ?: on $response->getQueryResult() can be risky. In PHP Protobuf, if the server sends an empty query_result field or if the getter returns an empty message object instead of null, the object will be truthy. This would overwrite the previously stored valid $queryResult with an empty one.

Using hasQueryResult() is the standard and safe way to check if a message field is present in the response.

        if ($response->hasQueryResult()) {
            $queryResult = $response->getQueryResult();
        }

}

// get final response and relevant info
if ($response) {
if ($queryResult) {
print(str_repeat('=', 20) . PHP_EOL);
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
Expand Down
Loading