Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Небольшие изменения в класс новой почты #63

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
84 changes: 84 additions & 0 deletions class_analysis.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
Попытка проанализировать класс и выделить из него части в другие подклассы,
которым здесь не место.

1. Геттеры и сеттеры.
key
connectionType
timeout
language
format (Format of returned data by methods (json, xml, array))

2.
prepare(); //Prepare data before return it
array2xml();
request(); //Make request to NovaPoshta API
model(); //Set current model and empties method and params properties.
method(); //Set method of current model property and empties params properties.
params(); //Set params of current method/property property
execute(); //Execute request to NovaPoshta API

documentsTracking(); //Get tracking information by track number

getCities(); //Get cities of company NovaPoshta
getWarehouses(); //Get warehouses by city
getWarehousesTypes(); //Get warehouse types
findNearestWarehouse(); //Get 5 nearest warehouses by array of strings
getWarehouse(); //Get one warehouse by city name and warehouse's description
getStreet(); //Get streets list by city and/or search string
findArea(); //Find current area in list of areas
getArea(); //Get area by name or by ID
getAreas(); //Get areas list by city and/or search string
findCityByRegion(); //Find city from list by name of region
getCity(); //Get city by name and region (if it needs)
__call(); //Magic method of calling functions (uses for calling Common Model of NovaPoshta API)


delete(); //Delete method of current model
update(); //Update method of current model
save(); //Save method of current model


getCounterparties(); //getCounterparties() function of model Counterparty
cloneLoyaltyCounterpartySender(); //cloneLoyaltyCounterpartySender() function of model Counterparty
getCounterpartyContactPersons(); //getCounterpartyContactPersons() function of model Counterparty.
getCounterpartyAddresses(); //getCounterpartyAddresses() function of model Counterparty.
getCounterpartyOptions(); //getCounterpartyOptions() function of model Counterparty.
getCounterpartyByEDRPOU(); getCounterpartyByEDRPOU() function of model Counterparty.


getDocumentPrice(); //Get price of delivery between two cities.
getDocumentDeliveryDate(); //Get approximately date of delivery between two cities.
getDocumentList(); //Get documents list.
getDocument(); //Get document info by ID.

generateReport(); //Generetes report by Document refs.

checkInternetDocumentRecipients(); //Check required fields for new InternetDocument and set defaults.
checkInternetDocumentParams(); //Check required params for new InternetDocument and set defaults.
newInternetDocument(); //Create Internet Document by.


printGetLink(); //Get only link on internet document for printing.
printDocument(); //printDocument method of InternetDocument model.
printMarking(); //printMarkings method of InternetDocument model.





















27 changes: 27 additions & 0 deletions src/Delivery/Array2Xml.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php
class Array2Xml
{
/**
* Converts array to xml.
*
* @param array $array
* @param \SimpleXMLElement|bool $xml
*/
public function array2xml(array $array, $xml = false)
{
if ($xml) {
$xml = new \SimpleXMLElement('<root/>');
}
foreach ($array as $key => $value) {
if (is_numeric($key)) {
$key = 'item';
}
if (is_array($value)) {
$this->array2xml($value, $xml->addChild($key));
} else {
$xml->addChild($key, $value);
}
}
return $xml->asXML();
}
}
131 changes: 22 additions & 109 deletions src/Delivery/NovaPoshtaApi2.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<?php

namespace LisDev\Delivery;
use PrepareReturnData;
use Array2Xml;


/**
* Nova Poshta API Class.
Expand Down Expand Up @@ -200,52 +203,12 @@ public function getFormat()
return $this->format;
}

/**
* Prepare data before return it.
*
* @param string|array $data
*
* @return mixed
*/
private function prepare($data)
{
// Returns array
if ('array' == $this->format) {
$result = is_array($data)
? $data
: json_decode($data, true);
// If error exists, throw Exception
if ($this->throwErrors and array_key_exists('errors', $result) and $result['errors']) {
throw new \Exception(is_array($result['errors']) ? implode("\n", $result['errors']) : $result['errors']);
}
return $result;
}
// Returns json or xml document
return $data;
}


/**
* Converts array to xml.
*
* @param array $array
* @param \SimpleXMLElement|bool $xml
* Я не могу понять нужно выносить этот метод в отдельный класс
* или он является фундаметном в этом классе NovaPoshtaApi2
*/
private function array2xml(array $array, $xml = false)
{
(false === $xml) and $xml = new \SimpleXMLElement('<root/>');
foreach ($array as $key => $value) {
if (is_numeric($key)) {
$key = 'item';
}
if (is_array($value)) {
$this->array2xml($value, $xml->addChild($key));
} else {
$xml->addChild($key, $value);
}
}
return $xml->asXML();
}

/**
* Make request to NovaPoshta API.
*
Expand All @@ -268,11 +231,25 @@ private function request($model, $method, $params = null)
'methodProperties' => $params,
);
$result = array();

$prepare = new PrepareReturnData();
$array2xml = new Array2Xml();

/*
* Замечание R1KO:
* На самом деле логику преобразования данных в нужный формат стоило вынести в отдельную иерархию абстракций, как раз таки в PrepareReturnData.
* Здесь тоже самое, я не понимаю как вынести это преобразование из метода реквест.
*
*/
// Convert data to neccessary format
$post = 'xml' == $this->format
Copy link

Choose a reason for hiding this comment

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

На самом деле логику преобразования данных в нужный формат стоило вынести в отдельную иерархию абстракций, как раз таки в PrepareReturnData

? $this->array2xml($data)
? $array2xml->array2xml($data)
: json_encode($data);

/*
* Здесь тоже самое, я не понимаю как вынести этот транспорт из метода реквест, чтобы потом в нём использовать.
Copy link

Choose a reason for hiding this comment

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


public function __construct($key, $language = 'ru', $throwErrors = false, ConnectionInterface $connection)

$this->connection->getData();


class CurlConnection implements ConnectionInterface {
// implementation
}

*
*/
if ('curl' == $this->getConnectionType()) {
Copy link

Choose a reason for hiding this comment

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

Этому здесь не место. Транспорт нужно выносить отдельно от логики

$ch = curl_init($url);
if (is_resource($ch)) {
Expand Down Expand Up @@ -307,7 +284,7 @@ private function request($model, $method, $params = null)
)));
}

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

/**
Expand Down Expand Up @@ -1047,69 +1024,5 @@ public function newInternetDocument($sender, $recipient, $params)
return $this->model('InternetDocument')->save($paramsInternetDocument);
}

/**
* Get only link on internet document for printing.
*
* @param string $method Called method of NovaPoshta API
* @param array $documentRefs Array of Documents IDs
* @param string $type (html_link|pdf_link)
*
* @return mixed
*/
protected function printGetLink($method, $documentRefs, $type)
{
$data = 'https://my.novaposhta.ua/orders/'.$method.'/orders[]/'.implode(',', $documentRefs)
.'/type/'.str_replace('_link', '', $type)
.'/apiKey/'.$this->key;
// Return data in same format like NovaPoshta API
return $this->prepare(
array(
'success' => true,
'data' => array($data),
'errors' => array(),
'warnings' => array(),
'info' => array(),
)
);
}

/**
* printDocument method of InternetDocument model.
*
* @param array|string $documentRefs Array of Documents IDs
* @param string $type (pdf|html|html_link|pdf_link)
*
* @return mixed
*/
public function printDocument($documentRefs, $type = 'html')
{
$documentRefs = (array) $documentRefs;
// If needs link
if ('html_link' == $type or 'pdf_link' == $type) {
return $this->printGetLink('printDocument', $documentRefs, $type);
}
// If needs data
return $this->request('InternetDocument', 'printDocument', array('DocumentRefs' => $documentRefs, 'Type' => $type));
}

/**
* printMarkings method of InternetDocument model.
*
* @param array|string $documentRefs Array of Documents IDs
* @param string $type (pdf|new_pdf|new_html|old_html|html_link|pdf_link)
*
* @return mixed
*/
public function printMarkings($documentRefs, $type = 'new_html', $size = '85x85')
{
$documentRefs = (array) $documentRefs;
$documentSize = $size === '85x85' ? '85x85' : '100x100';
$method = 'printMarking'.$documentSize;
// If needs link
if ('html_link' == $type or 'pdf_link' == $type) {
return $this->printGetLink($method, $documentRefs, $type);
}
// If needs data
return $this->request('InternetDocument', $method, array('DocumentRefs' => $documentRefs, 'Type' => $type));
}
}
50 changes: 50 additions & 0 deletions src/Delivery/PrepareReturnData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

class PrepareReturnData
{
/**
* @var string Format of returned data - array, json, xml
*/
protected $format = 'array';

/**
* @var bool Throw exceptions when in response is error
*/
protected $throwErrors = false;

/**
* Prepare data before return it.
*
* @param string|array $data
*
* @return mixed
*/
public function prepare($data)
{
// Returns array
/* if ('array' == $this->format) {
$result = is_array($data)
? $data
: json_decode($data, true);
// If error exists, throw Exception
if ($this->throwErrors and array_key_exists('errors', $result) and $result['errors']) {
throw new \Exception(is_array($result['errors']) ? implode("\n", $result['errors']) : $result['errors']);
}
return $result;
}
// Returns json or xml document
return $data;
*/
// Returns json or xml document
if ($this->format != 'array') return $data;

$result = is_array($data)
? $data
: json_decode($data, true);
// If error exists, throw Exception
if ($this->throwErrors and array_key_exists('errors', $result) and $result['errors']) {
throw new \Exception(is_array($result['errors']) ? implode("\n", $result['errors']) : $result['errors']);
}
return $result;
}
}
Loading