Skip to content

Commit

Permalink
- ActiveRecord. Обновлены комментарии. Убрана лишние подключения (use…
Browse files Browse the repository at this point in the history
… ...). При обработке ошибки в функция insert/updateInternal отслеживаем исключение GuzzleHttp\Exception\ClientException вместо \Exception.

- Command. Обновлены комментарии. Убрана лишние подключения (use ...). Обновлены функции queryAll, queryOne. Функция queryOne теперь поддерживает возмозмость поиска одной записи (через обращение к списку).
- Connection. Обновлены комментарии. Убрана лишние подключения (use ...).
- DebugPanel. Исправлен баг: иногда значение массива $timing[2] может быть строка. Добавлен код определение мтода запроса к странице. Если метод GET то отображаются ссылки "run query", "to new tab", При других методах ссылки не позволяют повторить запрос (поэтому и убраны)
- Query. Добавлена функция prepare().
- QueryBuilder. Теперь наследуемся от yii\base\Object вместо yii\db\QueryBuilder. В связи с этим добавлены новые параметры, функции и удалены неиспользуемые функции.
- RestDataProvider. Обновлены подключения (use ...).
- RestQuery. Добавлена функция removeDuplicatedModels. Обновлена функция one. Раньше она не корректно обрабатывала код : Contact::find()->where(['email' => $email])->one
  • Loading branch information
ApexWire committed Sep 23, 2016
1 parent 1f37efb commit c58a3bf
Show file tree
Hide file tree
Showing 9 changed files with 277 additions and 130 deletions.
15 changes: 13 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
apexwire/yii2-restclient changelog
---------------------------

## 0.3 Under development
## 0.4 Under development

- Поиск сломал страницу просмотра #10

## 0.3 2016-09-23

- ActiveRecord. Обновлены комментарии. Убрана лишние подключения (use ...). При обработке ошибки в функция insert/updateInternal отслеживаем исключение GuzzleHttp\Exception\ClientException вместо \Exception.
- Command. Обновлены комментарии. Убрана лишние подключения (use ...). Обновлены функции queryAll, queryOne. Функция queryOne теперь поддерживает возмозмость поиска одной записи (через обращение к списку).
- Connection. Обновлены комментарии. Убрана лишние подключения (use ...).
- DebugPanel. Исправлен баг: иногда значение массива $timing[2] может быть строка. Добавлен код определение мтода запроса к странице. Если метод GET то отображаются ссылки "run query", "to new tab", При других методах ссылки не позволяют повторить запрос (поэтому и убраны)
- Query. Добавлена функция prepare().
- QueryBuilder. Теперь наследуемся от yii\base\Object вместо yii\db\QueryBuilder. В связи с этим добавлены новые параметры, функции и удалены неиспользуемые функции.
- RestDataProvider. Обновлены подключения (use ...).
- RestQuery. Добавлена функция removeDuplicatedModels. Обновлена функция one. Раньше она не корректно обрабатывала код : Contact::find()->where(['email' => $email])->one
- Поиск сломал страницу просмотра #10

## 0.2 2016-03-17

Expand Down
35 changes: 15 additions & 20 deletions src/ActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,14 @@

namespace yii\restclient;

use GuzzleHttp\Exception\ClientException;
use yii\base\InvalidConfigException;
use yii\base\NotSupportedException;
use yii\db\ActiveQueryInterface;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use GuzzleHttp\Exception\ClientException;
use yii\helpers\Json;

/**
Expand All @@ -30,17 +28,18 @@
class ActiveRecord extends BaseActiveRecord
{
/**
* {@inheritdoc}
* @return null|Connection
* @throws InvalidConfigException
*/
public static function getDb()
{
return \Yii::$app->get(Connection::getDriverName());
}

/**
* {@inheritdoc}
* @inheritdoc
*
* @return RestQuery the newly created [[RestQuery]] instance.
* @return RestQuery
*/
public static function find($options = [])
{
Expand All @@ -53,23 +52,23 @@ public static function find($options = [])
}

/**
* {@inheritdoc}
* @inheritdoc
*/
public static function findAll($condition, $options = [])
{
return static::find($options)->andWhere($condition)->all();
}

/**
* {@inheritdoc}
* @inheritdoc
*/
public static function primaryKey()
{
return ['id'];
}

/**
* {@inheritdoc}
* @inheritdoc
*/
public function attributes()
{
Expand All @@ -85,7 +84,7 @@ public static function modelName()
}

/**
* {@inheritdoc}
* @inheritdoc
*/
public function insert($runValidation = true, $attributes = null)
{
Expand All @@ -110,10 +109,9 @@ public function insert($runValidation = true, $attributes = null)
$changedAttributes = array_fill_keys(array_keys($values), null);
$this->setOldAttributes($values);
$this->afterSave(true, $changedAttributes);
} catch (\Exception $e) {
} catch (ClientException $e) {

if ($e->getCode() == 422) {

$res = $e->getResponse()->getBody()->getContents();

if (preg_grep('|application/json|i', $e->getResponse()->getHeader('Content-Type'))) {
Expand All @@ -136,7 +134,7 @@ public function insert($runValidation = true, $attributes = null)
}

/**
* {@inheritdoc}
* @inheritdoc
*/
protected function updateInternal($attributes = null)
{
Expand Down Expand Up @@ -165,7 +163,7 @@ protected function updateInternal($attributes = null)
}

$this->afterSave(false, $changedAttributes);
} catch (\Exception $e) {
} catch (ClientException $e) {

if ($e->getCode() == 422) {

Expand All @@ -192,7 +190,7 @@ protected function updateInternal($attributes = null)


/**
* {@inheritdoc}
* @inheritdoc
*/
public function delete($options = [])
{
Expand All @@ -207,7 +205,6 @@ public function delete($options = [])
);

$result = true;

$this->setOldAttributes(null);
$this->afterDelete();
}
Expand All @@ -224,17 +221,15 @@ public function delete($options = [])
}

/**
* @return bool
* @inheritdoc
*/
public function getIsNewRecord()
{
return !$this->getPrimaryKey();
}

/**
* Destroys the relationship in current model.
*
* This method is not supported by HiArt.
* @inheritdoc
*/
public function unlinkAll($name, $delete = false)
{
Expand Down
39 changes: 27 additions & 12 deletions src/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@
namespace yii\restclient;

use yii\base\Component;
use yii\helpers\ArrayHelper;
use yii\helpers\Inflector;
use yii\helpers\Json;

/**
* Class Command class implements the API for accessing REST API.
Expand All @@ -26,11 +23,17 @@ class Command extends Component
* @var Connection
*/
public $db;

/**
* @var string|array the indexes to execute the query on. Defaults to null meaning all indexes
*/
public $index;

/**
* @var Query
*/
public $query;

/**
* @var array list of arrays or json strings that become parts of a query
*/
Expand All @@ -41,28 +44,40 @@ class Command extends Component
*/

/**
* @param array $options
* @return mixed
*/
public function queryAll($options = [])
public function queryAll()
{
$url = $this->index;
$query = is_array($this->queryParts) ? $this->queryParts : [];
$options = ArrayHelper::merge($query, $options);

return $this->db->get($url, $options);
return $this->db->get($url, $query);
}

/**
* @param array $options
* @return mixed
*/
public function queryOne($options = [])
public function queryOne()
{
//TODO: use $this->getOldPrimaryKey() yii\restclient\ActiveRecord
$url = $this->index . '/' . current($this->queryParts);
/* @var $query RestQuery */
$query = $this->query;

/* @var $class ActiveRecord */
$class = $query->modelClass;
$pks = $class::primaryKey();

$url = $this->index;
if (count($pks) == 1) {
$primaryKey = current($pks);
if (count($this->query->where) == 1 && isset($this->query->where[$primaryKey])) {

return $this->db->get($url . '/' . $this->query->where[$primaryKey]);
}
}

$query = is_array($this->queryParts) ? $this->queryParts : [];

return $this->db->get($url);
return $this->db->get($url, $query);
}

/**
Expand Down
5 changes: 2 additions & 3 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,10 @@
use Closure;
use GuzzleHttp\Client as Handler;
use GuzzleHttp\Psr7\Response;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use Yii;

/**
* Class Connection
Expand Down Expand Up @@ -210,6 +208,7 @@ public function delete($url, $query = [], $body = null, $raw = false)

/**
* Make request and check for error.
* @param string $method
* @param string $url URL
* @param array $query query options, (GET parameters)
* @param string $body request body, (POST parameters)
Expand Down
50 changes: 33 additions & 17 deletions src/DebugPanel.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use yii\helpers\Url;
use yii\log\Logger;
use yii\web\View;
use yii\base\InvalidConfigException;

/**
* Class DebugPanel Debugger panel that collects and displays Rest Client queries performed.
Expand Down Expand Up @@ -85,16 +86,20 @@ public function getDetail()
$i = 0;
// Try to get API URL
try {
$restclient = \Yii::$app->get('restclient');
$apiUrl = (StringHelper::endsWith($restclient->config['base_uri'], '/'))
? $restclient->config['base_uri']
: $restclient->config['base_uri'] . '/';
} catch (\yii\base\InvalidConfigException $e) {
$restClient = \Yii::$app->get('restclient');
$apiUrl = (StringHelper::endsWith($restClient->config['base_uri'], '/'))
? $restClient->config['base_uri']
: $restClient->config['base_uri'] . '/';
} catch (InvalidConfigException $e) {
// Pass
}

foreach ($timings as $logId => $timing) {
$time = date('H:i:s.', $timing[2]) . sprintf('%03d', (int)(($timing[2] - (int)$timing[2]) * 1000));
$duration = sprintf('%.1f ms', $timing[3] * 1000);
$time = $duration = '-';
if (is_double($timing[2])) {
$time = date('H:i:s.', $timing[2]) . sprintf('%03d', (int)(($timing[2] - (int)$timing[2]) * 1000));
$duration = sprintf('%.1f ms', $timing[3] * 1000);
}
$message = $timing[1];
$traces = $timing[4];

Expand All @@ -105,32 +110,43 @@ public function getDetail()
$url = $message;
$body = null;
}
$traceString = '';
if (!empty($traces)) {

if (($pos = mb_strpos($message, ' ')) !== false) {
$method = mb_substr($message, 0, $pos);
} else {
$method = null;
}

$traceString = '';
if (!empty($traces)) {
$traceString .= Html::ul($traces, [
'class' => 'trace',
'item' => function ($trace) {
return "<li>{$trace['class']}{$trace['type']}{$trace['function']}({$trace['line']})</li>";
},
]);
}
$ajaxUrl = Url::to(['rest-query', 'logId' => $logId, 'tag' => $this->tag]);
$runLink = Html::a('run query', $ajaxUrl, [
'class' => 'restclient-link',
'data' => ['id' => $i],
]) . '<br/>';
$newTabLink = Html::a('to new tab', $apiUrl . preg_replace('/^[A-Z]+\s+/', '', $url) . $body,
['target' => '_blank']) . '<br/>';

$runLink = $newTabLink = '';
if ($method == 'GET') {
$runLink = Html::a('run query',
Url::to(['rest-query', 'logId' => $logId, 'tag' => $this->tag]),
['class' => 'restclient-link', 'data' => ['id' => $i]]
);
$newTabLink = Html::a('to new tab',
$apiUrl . preg_replace('/^[A-Z]+\s+/', '', $url) . $body,
['target' => '_blank']
);
}

$url_encoded = Html::encode((isset($apiUrl)) ? str_replace(' ', ' ' . $apiUrl, $url) : $url);
$body_encoded = Html::encode($body);
$rows[] = <<<HTML
<tr>
<td style="width: 10%;">$time</td>
<td style="width: 10%;">$duration</td>
<td style="width: 75%;"><div><b>$url_encoded</b><br/><p>$body_encoded</p>$traceString</div></td>
<td style="width: 15%;">$runLink$newTabLink</td>
<td style="width: 15%;">$runLink<br/>$newTabLink</td>
</tr>
<tr style="display: none;" class="restclient-wrapper" data-id="$i">
<td class="time"></td>
Expand Down
13 changes: 11 additions & 2 deletions src/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@

namespace yii\restclient;

use Yii;
use yii\db\QueryInterface;
use yii\db\QueryTrait;
use yii\helpers\ArrayHelper;
use yii\base\NotSupportedException;
use Yii;

/**
* Class Query
Expand All @@ -25,6 +25,15 @@ class Query extends \yii\db\Query implements QueryInterface
/** @type string Название модели, которая используется для поиска */
public $searchModel;

/**
* @param QueryBuilder $builder
* @return $this
*/
public function prepare($builder)
{
return $this;
}

/**
* @param null $db
* @return mixed
Expand Down
Loading

0 comments on commit c58a3bf

Please sign in to comment.