Skip to content

Commit

Permalink
Merge pull request #29 from BenjaminMedia/bugfix-exception-on-empty-w…
Browse files Browse the repository at this point in the history
…idget

Added try catch to WidgetDocument->get() to avoid crash
  • Loading branch information
alfhen authored Aug 15, 2017
2 parents 3f0dcef + 543dfca commit 4de21af
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 9 deletions.
21 changes: 21 additions & 0 deletions src/Bonnier/WP/Cxense/Exceptions/WidgetException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
/**
* WidgetMissingId exception file
*/

namespace Bonnier\WP\Cxense\Exceptions;

/**
* WidgetMissingId class
*/
class WidgetException extends \Exception {

/**
* Constructor
*
* @return \Bonnier\WP\Cxense\Exceptions\WidgetException
*/
public function __construct($strMessage = '') {
return parent::__construct($strMessage, 20);
}
}
27 changes: 18 additions & 9 deletions src/Bonnier/WP/Cxense/Services/WidgetDocument.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

namespace Bonnier\WP\Cxense\Services;

use Bonnier\WP\Cxense\Exceptions\HttpException;
use Bonnier\WP\Cxense\Exceptions\WidgetException;
use Bonnier\WP\Cxense\Exceptions\WidgetMissingId;
use Bonnier\WP\Cxense\Http\HttpRequest;
use Bonnier\WP\Cxense\Settings\SettingsPage;
Expand Down Expand Up @@ -86,11 +88,11 @@ public function set_settings(SettingsPage $objSettings) {
*/
public function get_documents() {

$objDocuments = $this->set_categories()->set_parameters()->get();
$objDocuments = $this->set_categories()->set_parameters()->get()->items ?? [];

return [
'totalCount' => count($objDocuments->items),
'matches' => $this->parse_documents($objDocuments->items)
'totalCount' => count($objDocuments),
'matches' => $this->parse_documents($objDocuments)
];
}

Expand All @@ -100,7 +102,7 @@ public function get_documents() {
* @return null
*/
private function validate_widget_id() {
if (!isset($this->arrInput['widgetId'])) {
if (!isset($this->arrInput['widgetId']) && is_admin()) {
throw new WidgetMissingId('Missing request "widgetId" key!');
}
}
Expand All @@ -114,10 +116,17 @@ private function get() {

$this->set_widget_id();

$objResponse = HttpRequest::get_instance()->post('public/widget/data', [
'body' => json_encode($this->arrPayload)
]);

try {
$objResponse = HttpRequest::get_instance()->post('public/widget/data', [
'body' => json_encode($this->arrPayload)
]);
} catch (HttpException $exception) {
if(is_admin()) {
throw new WidgetException('Failed to load widget:' . $exception->getMessage());
}
return null;
}

return json_decode($objResponse->getBody());
}

Expand Down Expand Up @@ -172,4 +181,4 @@ private function parse_documents(array $arrDocuments) {

return $arrCollection;
}
}
}
1 change: 1 addition & 0 deletions wp-cxense

0 comments on commit 4de21af

Please sign in to comment.