Skip to content

Commit

Permalink
Added connection type property: curl (default) | file_get_content
Browse files Browse the repository at this point in the history
  • Loading branch information
lis-dev committed Mar 30, 2015
1 parent 41ff3c8 commit 44e964c
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 20 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,23 @@ https://github.com/lis-dev/nova-poshta-api-2/archive/master.zip
```php
$np = new NovaPoshtaApi2('Ваш_ключ_API_2.0');
```

## Создание экземпляра класса (с расширенными параметрами)
Рекомендуется использовать, если необходимо получать данные на языке, отличном от русского, выбрасывать Exception при ошибке запроса, или при отсутствии установленной библиотеки curl на сервере
```php
$np = new NovaPoshtaApi2(
'Ваш_ключ_API_2.0',
'ru', // Язык возвращаемых данных: ru (default) | ua | en
FALSE, // При ошибке в запросе выбрасывать Exception: FALSE (default) | TRUE
'curl' // Используемый механизм запроса: curl (defalut) | file_get_content
);
```

## Получение информации о трек-номере
```php
$result = $np->documentsTracking('59000000000000');
```

## Получение сроков доставки
```php
// Получение кода города по названию города и области
Expand Down
58 changes: 48 additions & 10 deletions src/Delivery/NovaPoshtaApi2.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ class NovaPoshtaApi2 {
*/
protected $language = 'ru';

/**
* @var string $connectionType Connection type (curl | file_get_contents)
*/
protected $connectionType = 'curl';

/**
* @var string $areas Areas (loaded from file, because there is no so function in NovaPoshta API 2.0)
*/
Expand All @@ -58,13 +63,15 @@ class NovaPoshtaApi2 {
* @param string $key NovaPoshta API key
* @param string $language Default Language
* @param bool $throwErrors Throw request errors as Exceptions
* @param bool $connectionType Connection type (curl | file_get_contents)
* @return NovaPoshtaApi2
*/
function __construct($key, $language = 'ru', $throwErrors = FALSE) {
function __construct($key, $language = 'ru', $throwErrors = FALSE, $connectionType = 'curl') {
$this->throwErrors = $throwErrors;
return $this
->setKey($key)
->setLanguage($language)
->setConnectionType($connectionType)
->model('Common');
}

Expand All @@ -88,6 +95,26 @@ function getKey() {
return $this->key;
}

/**
* Setter for $connectionType property
*
* @param string $connectionType Connection type (curl | file_get_contents)
* @return this
*/
function setConnectionType($connectionType) {
$this->connectionType = $connectionType;
return $this;
}

/**
* Getter for $connectionType property
*
* @return string
*/
function getConnectionType() {
return $this->connectionType;
}

/**
* Setter for language property
*
Expand Down Expand Up @@ -191,15 +218,26 @@ private function request($model, $method, $params = NULL) {
? $this->array2xml($data)
: $post = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: '.($this->format == 'xml' ? 'text/xml' : 'application/json')));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($ch);
curl_close($ch);
if ($this->getConnectionType() == 'curl') {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: '.($this->format == 'xml' ? 'text/xml' : 'application/json')));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($ch);
curl_close($ch);
} else {
$result = file_get_contents($url, null, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded;\r\n",
'content' => $post,
),
)));
}

return $this->prepare($result);
}

Expand Down
45 changes: 35 additions & 10 deletions tests/NovaPoshtaApi2Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,23 @@ function setUp() {
// Create new instance
$this->np = new NovaPoshtaApi2($this->key);
}

/**
* Test connectin via file_get_contents()
*/
function testSetConnectionType() {
$result = $this->np->setConnectionType('file_get_contents');
$this->assertInstanceOf('LisDev\Delivery\NovaPoshtaApi2', $result);
}

/**
* getConnectionType()
*/
function testGetConnectionType() {
$result = $this->np->getConnectionType();
$this->assertNotEmpty($result);
}

/**
* getKey()
*/
Expand All @@ -57,6 +74,14 @@ function testDocumentsTrackingResultArray() {
$this->assertTrue($result['success']);
}

/**
* Test request via file_get_content
*/
function testRequestViaFileGetContent() {
$result = $this->np->setConnectionType('file_get_content')->documentsTracking('59000082032106');
$this->assertTrue($result['success']);
}

/**
* documentsTracking() result in json
*/
Expand Down Expand Up @@ -493,16 +518,6 @@ function testGetDocumentList($params = NULL) {
return $result['data'][0]['Ref'];
}

/**
* getDocument()
*
* @depends testGetDocumentList
*/
function testGetDocument($ref) {
$result = $this->np->getDocument($ref);
$this->assertTrue($result['success']);
}

/**
* generateReport()
*/
Expand Down Expand Up @@ -566,6 +581,16 @@ function testNewInternetDocument($sender) {
return $result['data'][0]['Ref'];
}

/**
* getDocument()
*
* @depends testNewInternetDocument
*/
function testGetDocument($ref) {
$result = $this->np->getDocument($ref);
$this->assertTrue($result['success']);
}

/**
* printDocument()
*
Expand Down

0 comments on commit 44e964c

Please sign in to comment.