Current path: home/webdevt/cryptoimpot.fr/module/Application/src/Controller/
?? Go up: /home/webdevt/cryptoimpot.fr/module/Application/src
<?php
namespace Application\Controller;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;
use Laminas\Mail\Message;
use Laminas\Mime;
use Laminas\Mail\Transport\Sendmail as SendmailTransport;
use Exception;
class CryptoController extends AbstractActionController
{
const ROUTE_LISTE = 'admin/crypto';
const ROUTE_SHOW = 'admin/crypto/show-crypto';
public function getEntityManager()
{
return $this->entityManager;
}
/**
* Entity manager.
* @var Doctrine\ORM\EntityManager
*/
private $entityManager;
/**
* Auth manager.
* @var User\Service\AuthManager
*/
private $authManager;
/**
* User manager.
* @var User\Service\UserManager
*/
private $userManager;
/**
* config
* @var array
*/
private $config;
/**
* Constructor.
*/
public function __construct($entityManager, $authManager, $userManager, $config)
{
$this->entityManager = $entityManager;
$this->authManager = $authManager;
$this->userManager = $userManager;
$this->config = $config;
}
public function getConfig()
{
return $this->config;
}
public function indexAction()
{
// if ($user = $this->currentUser()) {
//
// } else {
// return $this->redirect()->toRoute(\Application\Controller\UserController::ROUTE_LOGIN);
// }
// if (!$this->access('profile.any.view') &&
// !$this->access('profile.own.view', ['user'=>$user])) {
// return $this->redirect()->toRoute('not-authorized');
// }
/* Array with number item authorize per page */
$config = $this->getConfig();
$configNumber = $config['number_per_page_authorize'];
/* Init query option */
$queryOption = array();
/* Page number default */
$queryOption['page'] = $pageNumber = $this->params()->fromQuery('page', '1');
/* Display Table or List */
$queryOption['display'] = $displayState = $this->params()->fromQuery('display', 'table');
/* Number element display per page */
$nb_element_per_page = $this->params()->fromQuery('nb_element_per_page', '30');
$queryOption['nb_element_per_page'] = $_SESSION['countPerPage'] = in_array($nb_element_per_page, array('30', '60', '90')) ? $nb_element_per_page : '30';
/* List Sort by field */
$sort_by = $this->params()->fromQuery('sort_by', 'datetimeTransaction');
$colTable = array(
'id' => array(
'label' => 'Id',
'class' => 'col-sm-2',
'allowOrder' => true,
),
// 'logo' => array(
// 'label' => 'Logo',
// 'class' => 'col-sm-1',
// 'allowOrder' => true,
// ),
'code' => array(
'label' => 'Code',
'class' => 'col-sm-1',
'allowOrder' => true,
),
'name' => array(
'label' => 'Nom',
'class' => 'col-sm-1',
'allowOrder' => true,
),
'enable' => array(
'label' => 'Action',
'class' => 'col-sm-2',
'allowOrder' => true,
)
);
$queryOption['sort_by'] = 'dateTransaction';
/* List order ASC or DESC */
$sort = $this->params()->fromQuery('sort', 'ASC');
$queryOption['sort'] = in_array($sort, array('ASC', 'DESC')) ? $sort : 'ASC';
/* Form search */
$formSearch = new \Application\Form\SearchForm();
$request = $this->getRequest();
/* @var $request \Laminas\Http\Request */
$filterOption = null;
if ($request->isGet() && is_string($request->getQuery('search'))) {
$data = $request->getQuery()->toArray();
$formSearch->setInputFilter(new \Application\InputFilter\SearchInputFilter());
$formSearch->setData($data);
if ($formSearch->isValid()) {
$queryOption['search'] = $data['search'];
}
}
$orderOption = array(
'sort_by' => $queryOption['sort_by'],
'sort' => $queryOption['sort'],
);
/* Création Paginator */
//$criteria = array('statut' => 1);
$search = '';
if (isset($queryOption['search'])) {
//$criteria = array_merge($criteria, array('contenu' => "%{$queryOption['search']}%"));
$search = $queryOption['search'];
}
$orderBy = array($orderOption['sort_by'] => $orderOption['sort']);
$entityManager = $this->getEntityManager();
/* @var $entityManager \Doctrine\ORM\EntityManager */
$mapperDevise = new \Application\Mapper\DeviseMapper($entityManager);
$parametersManager = array(
// 'user' => $user,
'sort_by' => $queryOption['sort_by'],
'sort' => $queryOption['sort'],
'search' => isset($queryOption['search']) ? $queryOption['search'] : null
);
$paginator = $mapperDevise->getList($parametersManager, true);
//$allData = $ledgioMapper->getListByIdUser($user->getId(), $parametersManager, false);
//var_dump($allData);
// var_dump($warningLedgio);
/* Option affichage paginator */
$paginator->setItemCountPerPage((int)$queryOption['nb_element_per_page']);
$paginator->setCurrentPageNumber((int)$queryOption['page']);
/* Verify current page < to number pages */
/* set is not allow after getting pages */
$numberPages = $paginator->getPages()->pageCount;
if ((int)$queryOption['page'] > $numberPages) {
$queryOption['page'] = '1';
}
$this->layout('layout/layout-ledgio');
return new ViewModel(array(
'numberPages' => $numberPages,
'paginator' => $paginator,
//'warningLedgio' => $warningLedgio,
'queryOption' => $queryOption,
'colTable' => $colTable,
'formSearch' => $formSearch,
));
}
public function dateRange($first, $step = '+1 day', $last = 'today', $format = 'd-m-Y')
{
$dates = array();
$current = strtotime($first);
if ($last == 'today') {
$last = strtotime(date('d-m-Y'));
} else {
$last = strtotime($last);
}
while ($current <= $last) {
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
/*
* route /admin/crypto/update/
*/
public function updateCoursAutoAction()
{
$thisYear = date('Y');
//$lastYear = $thisYear - 5;
$lastYear = $thisYear - 1;
$dateFrom = $lastYear . '-01-01';
$dateTo = date('Y-m-d');
$cryptoCode = $this->params()->fromRoute('crypto', '1');
$mapperDevise = new \Application\Mapper\DeviseMapper($this->getEntityManager());
// $mapperCoursDevise = new \Application\Mapper\CoursDeviseMapper($this->getEntityManager());
$devise = $mapperDevise->findByCode($cryptoCode);
$asset = $devise->getCode();
set_time_limit(0);
$dsn = "mysql:host=localhost;dbname=ledgio";
$user = "ledgio";
$passwd = "jUH5DhzJrTvBxy88";
$this->pdo = new \PDO($dsn, $user, $passwd);
$this->market_dir_base = './data/crypto-cours';
if (!is_dir($this->market_dir_base))
mkdir($this->market_dir_base, 0777, true);
$this->fileLog = $this->market_dir_base . '/' . $dateFrom . '-' . $dateTo . '-' . $asset;
//$this->logMaarket($dateFrom, $dateTo, $asset);
if (is_file($this->fileLog)) {
unlink($this->fileLog);
}
//$this->logLine('"id", "devise", "cours_euro", "date_euro"', $this->fileLog);
$begin = new \DateTime($dateFrom);
$end = new \DateTime($dateTo);
$interval = \DateInterval::createFromDateString('1 day');
$period = new \DatePeriod($begin, $interval, $end);
$i = 1;
foreach ($this->pdo->query('SELECT id FROM devise WHERE code = "' . $asset . '"', \PDO::FETCH_ASSOC) as $row) {
$idAsset = $row['id'];
}
foreach ($period as $dt) {
$price = $this->getPrice($asset, $dt);
//var_dump($this->arrayIndexDevise);
//echo $this->arrayIndexDevise['ETH']; echo $asset; exit;
$str = $i++ . ',"' . $idAsset . '","' . $price . '","' . $dt->format('Y-m-d H:i:s') . '"';
//echo $str;
$this->logLine($str, $this->fileLog);
// $sql = "INSERT INTO users (name, surname, sex) VALUES (?,?,?)";
// $pdo->prepare($sql)->execute($data);
//
// verifier si enregistrement devise_id et date existe deja
$result = $this->pdo->query('SELECT id FROM `cours_devise` WHERE `devise_id` = "' . $idAsset . '" AND `date_cours` = "' . $dt->format('Y-m-d H:i:s') . '"', \PDO::FETCH_ASSOC);
if (empty($result->fetchColumn())) {
$this->pdo->query('INSERT INTO `cours_devise` (`id`, `devise_id`, `cours_euro`, `date_cours`) VALUES (NULL, ' . $idAsset . ', ' . $price . ', "' . $dt->format('Y-m-d H:i:s') . '");');
echo('INSERT INTO `cours_devise` (`id`, `devise_id`, `cours_euro`, `date_cours`) VALUES (NULL, ' . $idAsset . ', ' . $price . ', "' . $dt->format('Y-m-d H:i:s') . '");');
} else {
// var_dump($result->fetchColumn()); exit;
echo 'deja present';
}
}
}
protected function logLine($str, $file)
{
// var_dump($file); exit;
file_put_contents($file, $str . PHP_EOL, FILE_APPEND | LOCK_EX);
}
public function getPrice($asset, \DateTime $dateTime)
{
//@todo call data market
//$value = 0;
/*
tryConversion If set to false, it will try to get only direct trading values [ Default - true]
fsym REQUIRED The cryptocurrency symbol of interest [ Min length - 1] [ Max length - 10]
tsyms REQUIRED Comma separated cryptocurrency symbols list to convert into [ Min length - 1] [ Max length - 30]
ts The unix timestamp of interest
e The exchange to obtain data from (our aggregated average - CCCAGG - by default) [ Min length - 2] [ Max length - 30] [ Default - CCCAGG]
extraParams The name of your application (we recommend you send it) [ Min length - 1] [ Max length - 2000] [ Default - NotAvailable]
calculationType Type of average to calculate (Close - a Close of the day close price, MidHighLow - the average between the 24 H high and low, VolFVolT - the total volume to / the total volume from) [ Min length - 2] [ Max length - 30] [ Default - Close]
sign */
//$date = new DateTime($currentTime);
//$datestr = $date->format('Y-m-d');
//var_dump($currentTime);
$urlApi = 'https://min-api.cryptocompare.com/data/pricehistorical?fsym=&tsyms=EUR&ts=&api_key=fd3aea02118639009c4a4de12b5f8a0f4619b08a814e04e9fa0aafc678127ea2';
//echo $urlApi;
//exit;
//coinlayer
// Requesthttps://api.coinlayer.com/convert
// ? access_key = YOUR_ACCESS_KEY
// & from = BTC
// & to = ETH
// & amount = 10
$urlApi = 'https://min-api.cryptocompare.com/data/pricehistorical?';
// asset fsym
$urlApi .= 'fsym=' . $asset;
$urlApi .= '&tsyms=EUR';
$urlApi .= '&ts=' . $dateTime->format('U');
$urlApi .= '&api_key=fd3aea02118639009c4a4de12b5f8a0f4619b08a814e04e9fa0aafc678127ea2';
//echo $urlApi; exit;
// fetch data
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $urlApi);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$rawData = curl_exec($curl);
curl_close($curl);
// decode to array
$data = json_decode($rawData, true);
// echo $dateTime->format('Y-m-d H:i:s');
//var_dump($data); exit;
if (!isset($data[$asset])) {
// recherche id coinmarketcap
//throw new Exception('Market value not found');
// get id of crypto on cmc
// $url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/map';
//
// $headers = [
// 'Accepts: application/json',
// 'X-CMC_PRO_API_KEY: 5922b05c-4c84-47c6-a462-f303e6c209be'
// ];
// $qs = http_build_query($parameters); // query string encode the parameters
// $request = "{$url}?{$qs}"; // create the request URL
//
//
// $curl = curl_init(); // Get cURL resource
//// Set cURL options
// curl_setopt_array($curl, array(
// CURLOPT_URL => $request, // set the request URL
// CURLOPT_HTTPHEADER => $headers, // set the headers
// CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
// ));
//
// $response = curl_exec($curl); // Send the request, save the response
// print_r(json_decode($response)); // print json decoded response
// curl_close($curl); // Close request
//exit;
// var_dump($asset);
// exit;
// $url = 'https://pro-api.coinmarketcap.com/v1/tools/price-conversion';
// $parameters = [
// 'id' => '1',
// 'amount' => '1',
// 'convert' => 'EUR'
// ];
//
// $headers = [
// 'Accepts: application/json',
// 'X-CMC_PRO_API_KEY: 5922b05c-4c84-47c6-a462-f303e6c209be'
// ];
// $qs = http_build_query($parameters); // query string encode the parameters
// $request = "{$url}?{$qs}"; // create the request URL
//
//
// $curl = curl_init(); // Get cURL resource
//// Set cURL options
// curl_setopt_array($curl, array(
// CURLOPT_URL => $request, // set the request URL
// CURLOPT_HTTPHEADER => $headers, // set the headers
// CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
// ));
//
// $response = curl_exec($curl); // Send the request, save the response
// print_r(json_decode($response)); // print json decoded response
// curl_close($curl); // Close request
//exit;
}
//// https://nomics.com/docs/#section/General
// $urlApi = 'https://api.nomics.com/v1?';
// https://api.nomics.com/v1/markets?key=your-key-here
// // asset fsym
//
//
// $urlApi .= 'ids==' . $asset;
// $urlApi .= '&convert=EUR';
// $urlApi .= '&ts=' . $dateTime->format('U');
// $urlApi .= '&api_key=fd3aea02118639009c4a4de12b5f8a0f4619b08a814e04e9fa0aafc678127ea2';
//
// // fetch data
// $curl = curl_init();
// curl_setopt($curl, CURLOPT_URL, $urlApi);
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// $rawData = curl_exec($curl);
// curl_close($curl);
// 73db4525d47bff9731b96e71a2eef868
$price = $data[$asset]['EUR'];
/*
$arrayMarket = array(
'2019-04-09' => array('XXBT' => 3300, 'XETH' => 160, 'XLTC' => 290),
'2019-04-10' => array('XXBT' => 4000, 'XETH' => 190, 'XLTC' => 295),
'2019-04-11' => array('XXBT' => 4100, 'XETH' => 410, 'XLTC' => 300),
'2019-04-12' => array('XXBT' => 4050, 'XETH' => 480, 'XLTC' => 300),
'2019-04-13' => array('XXBT' => 4200, 'XETH' => 600, 'XLTC' => 320),
'2019-04-14' => array('XXBT' => 4230, 'XETH' => 250, 'XLTC' => 400),
'2019-04-15' => array('XXBT' => 3900, 'XETH' => 200, 'XLTC' => 500),
'2019-04-16' => array('XXBT' => 3000, 'XETH' => 450, 'XLTC' => 510),
'2019-04-17' => array('XXBT' => 2500, 'XETH' => 400, 'XLTC' => 520),
);
if (empty($arrayMarket[$datestr]) || empty($arrayMarket[$datestr][$asset])) {
throw new Exception('Market value not found');
}
* */
//$currentTime
/*
BTC ETH LTC
3300 160 290
4000 190 295
4100 410 300
4050 480 300
4200 600 320
4230 250 400
3900 200 500
3000 450 510
2500 400 520
* */
// if ($asset === 'XETH'){
// $value = 160;
// }
return $price;
}
public function showAction()
{
$cryptoCode = $this->params()->fromRoute('crypto', '1');
$mapperDevise = new \Application\Mapper\DeviseMapper($this->getEntityManager());
$mapperCoursDevise = new \Application\Mapper\CoursDeviseMapper($this->getEntityManager());
$devise = $mapperDevise->findByCode($cryptoCode);
$deviseCoursArray = $mapperCoursDevise->findByDevise($devise);
// var_dump($devise->getFirstHistoricalDataCmc());
$dateStartString = '01-01-2011';
$dateStart = new \DateTime($dateStartString);
$dateEnd = new \DateTime();
$arrayDates = $this->dateRange($dateStart->format('d-m-Y'));
$arrayDateCours = [];
foreach ($deviseCoursArray as $key => $deviseCours) {
$arrayDateCours[] = $deviseCours->getDateCours()->format('d-m-Y');
}
//var_dump($arrayDates);
//$arrayDates = ['2020-05-20'];
// $arrayDateCours = ['2020-05-19'];
$diffDates = array_diff($arrayDates, $arrayDateCours);
// var_dump($diffDates);
// var_dump($deviseCours);
return new ViewModel(array(
'devise' => $devise,
'deviseCours' => $deviseCoursArray,
'coursInexistantDate' => $diffDates,
'dateStart' => $dateStart,
'dateEnd' => $dateEnd
));
}
}