Initial Commit
This commit is contained in:
@@ -0,0 +1,485 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Classe generica che si interfaccia con le varie classi di risorsa da utilizzare con le funzione generiche delle query
|
||||
*
|
||||
* Versione: 1.0.2
|
||||
* Data Update: 16/02/2021
|
||||
*
|
||||
* Elenco Funzionalità implementate:
|
||||
*
|
||||
* - countTotal
|
||||
* - getList con paginazione
|
||||
* - getList con ricerche complete di parametri ORWHERE e ANDORWHERE
|
||||
* - getList con gestione completa dell'ordinamento in base alla stringa passata anche con valori multipli | array (rimane intatto)
|
||||
* - getList con selectList (opzionele) | '*'
|
||||
* - getList con joinData (opzionale) inclusa anche la possibilità di inserire join multipli nell'array
|
||||
* - getList con groupBy (opzionale)
|
||||
* # Per utilizzare getList e groupBy bisogna fare l'overload delle funzioni checkIfSetJoinData | checkIfSetGroupBy nel controller della risorsa
|
||||
* - countFiltered() non utilizza il getList
|
||||
* - getByColumnName()
|
||||
* - customQuery()
|
||||
* - inserito l'overload della funzione getList che ora è utilizzabile con due intestazioni di metodo "classica" o "con array di parametri"
|
||||
* - inserita la gestione dell'having per la getList
|
||||
*
|
||||
* Class App_Model_AbstractGeneric
|
||||
*/
|
||||
abstract class App_Model_AbstractGeneric
|
||||
{
|
||||
protected $_resources = array();
|
||||
|
||||
const JOIN_TABLE_NAME = "JOIN_TABLE_NAME";
|
||||
const JOIN_CONDITION_NAME = "JOIN_CONDITION_NAME";
|
||||
const JOIN_COLUMNS_NAME = "JOIN_COLUMNS_NAME";
|
||||
const JOIN_TYPE = "JOIN_TYPE";
|
||||
const JOIN_FUNCTION_NAME_ALLOWED = array('join', 'joinInner', 'joinLeft', 'joinRight', 'joinFull', 'joinCross', 'joinNatural');
|
||||
|
||||
const ALLOWED_GETLIST_ARRAY_OPTIONS = array('page', 'count', 'where', 'order', 'selectList', 'joinOptions', 'groupBy', 'fetchRow', 'having');
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return App_Model_Resource_Abstract
|
||||
* @throws App_Controller_Errors_WebServiceError
|
||||
*/
|
||||
public function getResource($name)
|
||||
{
|
||||
|
||||
if (!isset($this->_resources[$name])) {
|
||||
$class = implode('_', array(
|
||||
$this->_getNamespace(),
|
||||
'Model_Resources',
|
||||
ucfirst($name)));
|
||||
|
||||
//Controllo l'esistenza della classe
|
||||
if (!class_exists($class)) {
|
||||
throw new App_Controller_Errors_WebServiceError("Errore generazione la classe risorsa '$class' potrebbe non esistere");
|
||||
}
|
||||
|
||||
$this->_resources[$name] = new $class();
|
||||
}
|
||||
|
||||
return $this->_resources[$name];
|
||||
}
|
||||
|
||||
private function _getNamespace()
|
||||
{
|
||||
$ns = explode('_', get_class($this));
|
||||
return $ns[0];
|
||||
}
|
||||
|
||||
/*====================================================================================================
|
||||
*======================= FUNZIONI GENERICHE PER OGNI TABELLA ==========================
|
||||
*====================================================================================================*/
|
||||
|
||||
/**
|
||||
* @param $resourceName
|
||||
* @param $info
|
||||
* @return mixed
|
||||
* @throws App_Controller_Errors_WebServiceError
|
||||
*/
|
||||
public function insert($resourceName, $info)
|
||||
{
|
||||
|
||||
return $this->getResource($resourceName)->insert($info);
|
||||
}
|
||||
|
||||
public function update($resourceName, $id, $info)
|
||||
{
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
$idString = (is_int($id)) ? " = $id" : " = '$id'";
|
||||
return $resource->update($info, $resource->getPrimaryKey() . $idString);
|
||||
}
|
||||
|
||||
public function updateWhere($resourceName, $condition, $info)
|
||||
{
|
||||
//Se passo un array di condizioni viene construita la stringa
|
||||
if (is_array($condition)) {
|
||||
$last_key = key(array_slice($condition, -1, 1, TRUE));
|
||||
$str = "";
|
||||
foreach ($condition as $key => $val) {
|
||||
$str .= str_replace('?', $val, $key);
|
||||
if ($key != $last_key) $str .= " AND ";
|
||||
}
|
||||
$condition = $str;
|
||||
}
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
return $resource->update($info, $condition);
|
||||
}
|
||||
|
||||
public function delete($resourceName, $id)
|
||||
{
|
||||
$resource = $this->getResource($resourceName);
|
||||
$idString = (is_int($id)) ? " = $id" : " = '$id'";
|
||||
return $resource->delete($resource->getPrimaryKey() . $idString);
|
||||
}
|
||||
|
||||
public function deleteWhere($resourceName, $condition)
|
||||
{
|
||||
//Se passo un array di condizioni viene construita la stringa
|
||||
if (is_array($condition)) {
|
||||
$last_key = key(array_slice($condition, -1, 1, TRUE));
|
||||
$str = "";
|
||||
foreach ($condition as $key => $val) {
|
||||
$str .= str_replace('?', $val, $key);
|
||||
if ($key != $last_key) $str .= " AND ";
|
||||
}
|
||||
$condition = $str;
|
||||
}
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
return $resource->delete($condition);
|
||||
}
|
||||
|
||||
public function getById($resourceName, $id)
|
||||
{
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
return $resource->getAdapter()->query('SELECT * FROM ' . $resource->getTableName() . ' WHERE ' . $resource->getPrimaryKey() . ' = ?', array($id))->fetch();
|
||||
}
|
||||
|
||||
public function getLastId($resourceName)
|
||||
{
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
return $resource->getAdapter()->query('SELECT id FROM ' . $resource->getTableName() . ' ORDER BY ' . $resource->getPrimaryKey() . ' DESC LIMIT 1')->fetchColumn(0);
|
||||
}
|
||||
|
||||
public function getCountTotal($resourceName)
|
||||
{
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
return $resource->getAdapter()->query('SELECT COUNT(*) as num FROM ' . $resource->getTableName())->fetchColumn(0);
|
||||
}
|
||||
|
||||
// FUNZIONE GET LIST CON OVERLOAD
|
||||
|
||||
public function getList()
|
||||
{
|
||||
$args = func_get_args();
|
||||
$functionName = (func_num_args() === 2 && is_array($args[1])) ? 'getListOptions' : 'getListDefault';
|
||||
return call_user_func_array(array(&$this, $functionName), $args);
|
||||
}
|
||||
|
||||
/**
|
||||
* #Overload
|
||||
* Funzione get list che accetta i parametri inseriti in un array in modo da non dover più rispettare l'ordine di inserimento
|
||||
*
|
||||
* @param $resourceName
|
||||
* @param array $options
|
||||
* @return Zend_Paginator
|
||||
* @throws Zend_Exception
|
||||
* @throws Zend_Paginator_Exception
|
||||
*/
|
||||
public function getListOptions($resourceName, array $options = [])
|
||||
{
|
||||
foreach ($options as $optionKey => $val) {
|
||||
if (!in_array($optionKey, self::ALLOWED_GETLIST_ARRAY_OPTIONS)) {
|
||||
throw new App_Controller_Errors_WebServiceError("'$optionKey' non e' una opzione valida per la funzione getList()");
|
||||
}
|
||||
}
|
||||
|
||||
return $this->getListDefault($resourceName,
|
||||
$options['page'], $options['count'], $options['where'],
|
||||
$options['order'], $options['selectList'], $options['joinOptions'],
|
||||
$options['groupBy'], $options['fetchRow'], $options['having']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Funzione getList completa (può sostituire anche la funzione getFilteredList)
|
||||
*
|
||||
* @param $resourceName
|
||||
* @param null $paged
|
||||
* @param null $count
|
||||
* @param array $where
|
||||
* @param null $order
|
||||
* @param string $selectList
|
||||
* @param null $joinData
|
||||
* @param null $groupBy
|
||||
* @param bool $fetchRow
|
||||
* @return Zend_Paginator
|
||||
* @throws Zend_Exception
|
||||
* @throws Zend_Paginator_Exception
|
||||
*/
|
||||
public function getListDefault($resourceName, $paged = null, $count = null, $where = array(), $order = null, $selectList = '*', $joinData = null, $groupBy = null, $fetchRow = false, $having = false)
|
||||
{
|
||||
$resource = $this->getResource($resourceName);
|
||||
|
||||
// definizione della select list
|
||||
$selectList = (!is_null($selectList)) ? $selectList : $resource->getDefaultSelectColumns();
|
||||
if (is_string($selectList)) {
|
||||
$selectList = explode(',', $selectList);
|
||||
}
|
||||
$select = $resource->getAdapter()->select()->from($resource->getTableName(), $selectList);
|
||||
|
||||
//Gestione dell'eventuale Join
|
||||
$joinData = (!is_null($joinData)) ? $joinData : $resource->getDefaultJoinData();
|
||||
if (is_array($joinData)) {
|
||||
$select = $this->applicateJoinData($select, $joinData);
|
||||
}
|
||||
|
||||
//gestione dei parametri di ricerca
|
||||
if (is_array($where)) {
|
||||
foreach ($where as $key => $value) {
|
||||
// se trovo l'operatore '#OR' o '#ANDOR' significa che devo applicare l'or per gli elementi passati nel campo value, NB: il value deve essere una string separata da virgole
|
||||
if (preg_match("/#OR/", $key)) { // #ANDOR accoda la query es: WHERE ... OR (nome_campo = ?)
|
||||
$select = $this->applicateOrWhere($select, $key, $value, '#OR');
|
||||
} else if (preg_match("/#ANDOR/", $key)) { // #ANDOR compone la query es: WHERE ... AND ( campo1 = ? OR campo2 = ?)
|
||||
|
||||
//salvo le condizioni presenti e resetto temporaneamente le condizini
|
||||
$oldWhereConditions = $select->getPart(Zend_Db_Select::WHERE);
|
||||
$select->reset(Zend_Db_Select::WHERE);
|
||||
|
||||
// genero le condizioni or
|
||||
$select = $this->applicateOrWhere($select, $key, $value, '#ANDOR');
|
||||
|
||||
// recupero le condizioni or generate e resetto di nuovo tutte le condizioni
|
||||
$orWhereConditions = $select->getPart(Zend_Db_Select::WHERE);
|
||||
$select->reset(Zend_Db_Select::WHERE);
|
||||
|
||||
// reimposto le vecchie condizioni e accodo le nuove condizioni or
|
||||
if ($oldWhereConditions) $select->where(implode(' ', $oldWhereConditions));
|
||||
$select->where(implode(' ', $orWhereConditions));
|
||||
|
||||
} else {
|
||||
//Di default utilizzo where con la AND
|
||||
$select->where($key, $value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Gestione dell'eventuale grouBy
|
||||
if ($groupBy) {
|
||||
$select->group($groupBy);
|
||||
}
|
||||
|
||||
//gestione dell'ordinamento
|
||||
$order = (!$order) ? $resource->getDefaultOrder() : $order;
|
||||
if (is_string($order)) {
|
||||
$tmpOrder = explode(',', $order);
|
||||
foreach ($tmpOrder as &$ord) {
|
||||
// il '.' serve a definire il nome della tabella altrimenti imposto quella di default della risorsa che chiama la query
|
||||
if (!preg_match("/\./", $ord)) {
|
||||
$ord = $resource->getTableName() . "." . trim($ord);
|
||||
}
|
||||
|
||||
// Se non esiste un verso di ordinamento assegno quello di default della risorsa per ogni campo ordinamento passato
|
||||
if (!preg_match("/(ASC|DESC|desc|asc)$/", $ord)) {
|
||||
$ord = explode(' ', trim($ord))[0] . ' ' . strtoupper($resource->getDefaultTipoOrder());
|
||||
}
|
||||
}
|
||||
|
||||
$order = $tmpOrder;
|
||||
}
|
||||
|
||||
$select->order($order);
|
||||
|
||||
//Gestione dell'eventuale grouBy
|
||||
if ($having && is_array($having)) {
|
||||
foreach (array_keys($having) as $key) {
|
||||
$select->having($key, $having[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($select->__toString(), true));
|
||||
|
||||
//Esecuzione della query di ricerca
|
||||
if (null !== $paged && null !== $count) {
|
||||
$adapter = new Zend_Paginator_Adapter_DbSelect($select);
|
||||
$paginator = new Zend_Paginator($adapter);
|
||||
$paginator->setItemCountPerPage($count)->setCurrentPageNumber((int)$paged);
|
||||
|
||||
return $paginator;
|
||||
}
|
||||
$stmt = $resource->getAdapter()->query($select->__toString());
|
||||
|
||||
//Gestione del Fetch
|
||||
if ($fetchRow)
|
||||
return $stmt->fetch();
|
||||
else
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $resourceName
|
||||
* @param $where
|
||||
* @param null $order
|
||||
* @param null $selectList
|
||||
* @param null $joinData
|
||||
* @param null $groupBy
|
||||
* @return Zend_Paginator
|
||||
* @throws Zend_Exception
|
||||
* @throws Zend_Paginator_Exception
|
||||
*/
|
||||
public function getFiltered($resourceName, $where, $order = null, $selectList = null, $joinData = null, $groupBy = null)
|
||||
{
|
||||
return $this->getList($resourceName, null, null, $where, $order, $selectList, $joinData, $groupBy, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Con questa funzione posso recuperare il numero di elementi di una tabella in base a parametri
|
||||
* @param $resourceName
|
||||
* @param $where
|
||||
*
|
||||
* @return Zend_Paginator
|
||||
*/
|
||||
public function countFiltered($resourceName, $where)
|
||||
{
|
||||
//Definizione della risorsa
|
||||
$resource = $this->getResource($resourceName);
|
||||
$select = $resource->getAdapter()->select()->from($resource->getTableName(), 'COUNT(*) as num');
|
||||
|
||||
//Applico le eventuali condizioni di ricerca
|
||||
foreach ($where as $key => $value) {
|
||||
$select->where($key, $value);
|
||||
}
|
||||
|
||||
$stmt = $resource->getAdapter()->query($select->__toString());
|
||||
|
||||
return $stmt->fetchColumn(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Questa funzione passato il nome della colonna su cui cercare cerca il valore scelto;
|
||||
* l'operatore di default è 'uguale'
|
||||
* altriemnti è possibile specificarne un altro trimete il parametro @op
|
||||
*
|
||||
* @param $resourceName
|
||||
* @param $columnName
|
||||
* @param $value
|
||||
* @param $fetchRow | Se impostato a true ritorna la riga come oggetto
|
||||
* @param $op
|
||||
* @param $joinData | per eseguire un join con altre tabelle
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getByColumnName($resourceName, $columnName, $value, $op = "=", $fetchRow = false, $order = null, $joinData = null)
|
||||
{
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
|
||||
//GESTIONE OPERATORI
|
||||
switch ($op) {
|
||||
case'LIKE':
|
||||
$value = "%" . $value . "%";
|
||||
break;
|
||||
case'LIKEPRE':
|
||||
$value = "%" . $value;
|
||||
break;
|
||||
case'LIKEPOST':
|
||||
$value = $value . "%";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
$select = $resource->getAdapter()->select()->from($resource->getTableName());
|
||||
|
||||
//Gestione dell'eventuale Join
|
||||
if (is_array($joinData)) {
|
||||
$select = $this->applicateJoinData($select, $joinData);
|
||||
}
|
||||
|
||||
$select->where($columnName . ' ' . $op . ' ?', $value);
|
||||
|
||||
if ($order != null && (is_array($order) || is_string($order))) {
|
||||
$select->order($order);
|
||||
}
|
||||
|
||||
if ($fetchRow) {
|
||||
if ($order != null && (is_array($order) || is_string($order))) {
|
||||
return $resource->fetchRow($resource->select()->where($columnName . ' ' . $op . ' ?', $value)->order($order));
|
||||
} else {
|
||||
return $resource->fetchRow($resource->select()->where($columnName . ' ' . $op . ' ?', $value));
|
||||
}
|
||||
} else {
|
||||
return $resource->getAdapter()->query($select->__toString())->fetch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $query
|
||||
* @param null $params
|
||||
* @param bool $fetchRow
|
||||
* @return mixed
|
||||
*
|
||||
* @throws App_Controller_Errors_WebServiceError
|
||||
*/
|
||||
public function customQuery($query, $params = null, $fetchRow = false)
|
||||
{
|
||||
|
||||
$resource = $this->getResource('Abstract');
|
||||
$stmt = $resource->getAdapter()->query($query, $params);
|
||||
|
||||
//Gestione del Fetch
|
||||
if ($fetchRow)
|
||||
return $stmt->fetch();
|
||||
else
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $select
|
||||
* @param $joinData
|
||||
* @return mixed
|
||||
*
|
||||
* @throws App_Controller_Errors_WebServiceError
|
||||
*/
|
||||
private function applicateJoinData($select, $joinData)
|
||||
{
|
||||
|
||||
if (!isset($joinData[0])) {
|
||||
if (!array_key_exists(self::JOIN_TABLE_NAME, $joinData))
|
||||
throw new App_Controller_Errors_WebServiceError("Nome tabella per il join non trovato");
|
||||
|
||||
if (!array_key_exists(self::JOIN_CONDITION_NAME, $joinData))
|
||||
throw new App_Controller_Errors_WebServiceError("Nome del campo di condizione per il join non trovato");
|
||||
|
||||
$colonne = (!$joinData[self::JOIN_COLUMNS_NAME]) ? array('*') : $joinData[self::JOIN_COLUMNS_NAME];
|
||||
$joinFunctionName = (in_array($joinData[self::JOIN_TYPE], self::JOIN_FUNCTION_NAME_ALLOWED)) ? $joinData[self::JOIN_TYPE] : 'join';
|
||||
|
||||
return $select->$joinFunctionName($joinData[self::JOIN_TABLE_NAME], $joinData[self::JOIN_CONDITION_NAME], $colonne);
|
||||
} else { // Gestione di più join contemporanei
|
||||
foreach ($joinData as $key => $join) {
|
||||
if (!array_key_exists(self::JOIN_TABLE_NAME, $join))
|
||||
throw new App_Controller_Errors_WebServiceError("Nome tabella per il join non trovato per il join index: [$key]");
|
||||
|
||||
if (!array_key_exists(self::JOIN_CONDITION_NAME, $join))
|
||||
throw new App_Controller_Errors_WebServiceError("Nome del campo di condizione per il join non trovato per il join index: [$key]");
|
||||
|
||||
$colonne = (!$join[self::JOIN_COLUMNS_NAME]) ? array('*') : $join[self::JOIN_COLUMNS_NAME];
|
||||
$joinFunctionName = (in_array($join[self::JOIN_TYPE], self::JOIN_FUNCTION_NAME_ALLOWED)) ? $join[self::JOIN_TYPE] : 'join';
|
||||
|
||||
$select->$joinFunctionName($join[self::JOIN_TABLE_NAME], $join[self::JOIN_CONDITION_NAME], $colonne);
|
||||
}
|
||||
return $select;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private function applicateOrWhere($select, string $keyNomeCampo, $valoriOr, string $op = '#OR')
|
||||
{
|
||||
|
||||
$valueOrDaApplicare = null;
|
||||
if (is_string($valoriOr))
|
||||
$valueOrDaApplicare = explode(',', $valoriOr);
|
||||
elseif (is_array($valoriOr))
|
||||
$valueOrDaApplicare = $valoriOr;
|
||||
|
||||
if (!$valueOrDaApplicare) {
|
||||
throw new App_Controller_Errors_WebServiceError("Valori per la condizione '$op' non validi per generare la query", App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_ERROR);
|
||||
}
|
||||
|
||||
$keyDaApplicare = str_replace($op, '=', $keyNomeCampo);
|
||||
|
||||
if (is_array($valueOrDaApplicare) && count($valueOrDaApplicare) > 0) {
|
||||
foreach ($valueOrDaApplicare as $val) {
|
||||
$select->orwhere($keyDaApplicare, $val);
|
||||
}
|
||||
}
|
||||
|
||||
return $select;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
abstract class App_Model_AbstractRest
|
||||
{
|
||||
protected $_resources = array();
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return Application_Model_RestResources_Generic
|
||||
*/
|
||||
public function getResource($name)
|
||||
{
|
||||
|
||||
if (!isset($this->_resources[$name])) {
|
||||
$class = implode('_', array(
|
||||
$this->_getNamespace(),
|
||||
'Model',
|
||||
'RestResources',
|
||||
ucfirst($name)));
|
||||
|
||||
//Controllo l'esistenza della classe [commentato perchè genera errore su alcune risorse]
|
||||
if (!class_exists($class)) {
|
||||
throw new App_Controller_Errors_WebServiceError("Errore di generazione per la classe risorsa rest '$class'. Potrebbe non esistere!");
|
||||
}
|
||||
|
||||
$this->_resources[$name] = new $class();
|
||||
}
|
||||
|
||||
return $this->_resources[$name];
|
||||
}
|
||||
|
||||
private function _getNamespace()
|
||||
{
|
||||
$ns = explode('_', get_class($this));
|
||||
return $ns[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $results
|
||||
* @param $page
|
||||
* @param $count
|
||||
* @return Zend_Paginator
|
||||
*
|
||||
* Questa funzione pasato un array lo converte in un oggetto Zend Paginator
|
||||
*/
|
||||
public function converResultsToZendPaginator($results,$page,$count){
|
||||
$dati = $this->getOffsetPaginatedArray($results['data'],$results['totalItem'],$page,$count);
|
||||
$results = Zend_Paginator::factory($dati);
|
||||
$results->setItemCountPerPage($count);
|
||||
$results->setCurrentPageNumber($page);
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $results
|
||||
* @param $totalItems
|
||||
* @param $page
|
||||
* @param $count
|
||||
* @return array
|
||||
* Funzione che crea un offset di oggetti per far si che il paginator conosca il numero totale di elemnti presenti
|
||||
*/
|
||||
public function getOffsetPaginatedArray($results,$totalItems,$page,$count){
|
||||
$dati = array();
|
||||
$rangeStart = (($page * $count) - $count) + 1;
|
||||
$rangeEnd = $page * $count;
|
||||
$rangeX = 0;
|
||||
|
||||
for($i = 0; $i < $totalItems ;$i++){
|
||||
if($i >= $rangeStart -1 && $i <= $rangeEnd -1){
|
||||
$dati[$i] = $results[$rangeX];
|
||||
$rangeX++;
|
||||
}else{
|
||||
$dati[$i] = array();
|
||||
}
|
||||
}
|
||||
|
||||
return $dati;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
class App_Model_Acl_Acl extends Zend_Acl
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
// ACL for default role
|
||||
$this->addRole(new Zend_Acl_Role('unregistered'))
|
||||
->add(new Zend_Acl_Resource('default'))
|
||||
->add(new Zend_Acl_Resource('auth'))
|
||||
->add(new Zend_Acl_Resource('v1'))
|
||||
->allow('unregistered', array('default', 'auth', 'v1'));
|
||||
|
||||
// ACL for user
|
||||
$this->addRole(new Zend_Acl_Role('user'), 'unregistered')
|
||||
->add(new Zend_Acl_Resource('user'))
|
||||
->allow('user', array('user'));
|
||||
|
||||
// ACL for administrator
|
||||
$this->addRole(new Zend_Acl_Role('admin'), array('user'))
|
||||
->add(new Zend_Acl_Resource('admin'))
|
||||
->add(new Zend_Acl_Resource('monitoring'))
|
||||
->allow('admin', array('admin', 'monitoring'));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
class App_Model_Acl_AclRestV1 extends Zend_Acl
|
||||
{
|
||||
/**
|
||||
* ACL che controlla in base al role dell'user se puo accedere a un determinato controller del web seervices
|
||||
*
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
|
||||
// ACL for default role
|
||||
$this->addRole(new Zend_Acl_Role('unregistered'))
|
||||
->add(new Zend_Acl_Resource('index'))
|
||||
->add(new Zend_Acl_Resource('error'))
|
||||
->add(new Zend_Acl_Resource('services'))
|
||||
->allow('unregistered', array('index','error','services'));
|
||||
|
||||
// ACL for user
|
||||
$this->addRole(new Zend_Acl_Role('user'), 'unregistered')
|
||||
->add(new Zend_Acl_Resource('emails'))
|
||||
->allow('user', array('emails'));
|
||||
|
||||
// ACL for administrator
|
||||
$this->addRole(new Zend_Acl_Role('admin'), 'user')
|
||||
->add(new Zend_Acl_Resource('users'))
|
||||
->allow('admin', array('users'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
|
||||
class App_Model_CurlHttpClient
|
||||
{
|
||||
|
||||
protected $_httpClient = null;
|
||||
protected $_urlNameServices;
|
||||
|
||||
public function __construct($urlName){
|
||||
|
||||
$this->_urlNameServices = $urlName;
|
||||
|
||||
$this->_httpClient = new Zend_Http_Client($urlName);
|
||||
$this->_httpClient->setConfig(array(
|
||||
'adapter' => 'Zend_Http_Client_Adapter_Curl',
|
||||
'maxredirects' => 0,
|
||||
'timeout' => 60,
|
||||
'ssltransport' => 'ssl'
|
||||
));
|
||||
}
|
||||
|
||||
/***** METODI COMUNI DELLE CHIMATE *****/
|
||||
|
||||
public function getCall($params){
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setParameterGet($params);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function postCall($dati,$formatJson = false){
|
||||
$this->_httpClient->setMethod('POST');
|
||||
if($formatJson)
|
||||
$this->_httpClient->setRawData(json_encode($dati),'application/json;charset=utf-8');
|
||||
else
|
||||
$this->_httpClient->setParameterPost($dati);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function putCall($dati,$formatJson = false){
|
||||
$this->_httpClient->setMethod('PUT');
|
||||
if($formatJson)
|
||||
$this->_httpClient->setRawData(json_encode($dati),'application/json;charset=utf-8');
|
||||
else
|
||||
$this->_httpClient->setParameterPost($dati);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function deleteCall($params){
|
||||
$this->_httpClient->setMethod('DELETE');
|
||||
$this->_httpClient->setParameterGet($params);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
/***** METODI PRIVATI PER GESTIRE LE CHIAMATE *****/
|
||||
|
||||
private function executeCall(){
|
||||
$httpResponse = $this->_httpClient->request();
|
||||
$headerResponse = $httpResponse->getHeaders();
|
||||
|
||||
if(preg_match('/application\/json/',$headerResponse['Content-type'])){
|
||||
$httpResponseBody = json_decode($httpResponse->getBody(),1);
|
||||
|
||||
if(json_last_error() !== JSON_ERROR_NONE){
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore codifica JSON:");
|
||||
Zend_Registry::get('log')->info(print_r($httpResponse,true));
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!$httpResponseBody['status'] && !$httpResponseBody['success']) {
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore 'httpResponse' no status or success code:");
|
||||
Zend_Registry::get('log')->info(print_r($httpResponseBody,true));
|
||||
throw new Exception($httpResponseBody['message'],$httpResponseBody['errorCode']);
|
||||
}
|
||||
}else{
|
||||
$httpResponseBody = $httpResponse->getBody();
|
||||
}
|
||||
|
||||
return $httpResponseBody;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
|
||||
abstract class App_Model_FcmFirebase
|
||||
{
|
||||
|
||||
const BASE_API_URL = "https://fcm.googleapis.com";
|
||||
const API_VERSION = "fcm";
|
||||
const SECRET_ID = "AAAAfg7FWPQ:APA91bHte0qwGR5J8wdfuUWJhU6-ehj_xXH6cOV6s2IFabm-86wBIwwUJsvwPmKD65PQ2HEl8SRzcy6EOl3GCc9K_StPgNpG8t84Zz5j7_uFKPCiHvblAb0xLk2eYYDsim4eBhvokv0s";
|
||||
|
||||
protected $_httpClient = null;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
|
||||
if ($this->_httpClient instanceof Zend_Http_Client) {
|
||||
//$this->_httpClient = $this->_httpClient;
|
||||
} else {
|
||||
$this->_httpClient = new Zend_Http_Client();
|
||||
$this->_httpClient->setConfig(array(
|
||||
'adapter' => 'Zend_Http_Client_Adapter_Curl',
|
||||
'maxredirects' => 0,
|
||||
'timeout' => 60,
|
||||
'ssltransport' => 'ssl'
|
||||
));
|
||||
$this->_httpClient->setHeaders('Authorization', 'key=' . self::SECRET_ID);
|
||||
}
|
||||
}
|
||||
|
||||
/***** METODI COMUNI DELLE CHIMATE *****/
|
||||
|
||||
public function postCall($dati)
|
||||
{
|
||||
$this->_httpClient->setMethod('POST');
|
||||
$this->_httpClient->setUri($this->getBaseUrl() . '/send');
|
||||
$this->_httpClient->setRawData(Zend_Json::encode($dati), 'application/json;charset=utf-8');
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
/***** METODI PRIVATI PER GESTIRE LE CHIAMATE *****/
|
||||
|
||||
private function getBaseUrl()
|
||||
{
|
||||
return self::BASE_API_URL . "/" . self::API_VERSION;
|
||||
}
|
||||
|
||||
private function executeCall()
|
||||
{
|
||||
$httpResponse = $this->_httpClient->request();
|
||||
|
||||
/*if($this->_ipManager->allowedIp()){
|
||||
Zend_Registry::get('log')->info(print_r($httpResponse,true));
|
||||
}*/
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($this->_httpClient->getLastRequest(), true));
|
||||
|
||||
$httpResponseEncoded = json_decode($httpResponse->getBody(), 1);
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($httpResponseEncoded, true));
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore codifica JSON:");
|
||||
Zend_Registry::get('log')->info(print_r($httpResponse, true));
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->_httpClient->getLastResponse()->getStatus() != '200' || $httpResponseEncoded['status'] == 'error') {
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore status response " . $this->_httpClient->getLastResponse()->getStatus());
|
||||
Zend_Registry::get('log')->info(print_r($httpResponseEncoded, true));
|
||||
throw new App_Exception_ResponseCloudException($httpResponseEncoded['message'], $httpResponseEncoded['errorCode']);
|
||||
}
|
||||
|
||||
return $httpResponseEncoded;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
class App_Model_Mail extends Zend_Mail
|
||||
{
|
||||
/**
|
||||
* Sets the HTML body for the message
|
||||
*
|
||||
* @param string $html
|
||||
* @param string $charset
|
||||
* @param string $encoding
|
||||
* @return Zend_Mail Provides fluent interface
|
||||
*/
|
||||
public function setBodyHtml($html, $charset = null, $encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE, $preload_images = true)
|
||||
{
|
||||
$preload_images = false;
|
||||
try {
|
||||
if ($preload_images) {
|
||||
|
||||
$this->setType(Zend_Mime::MULTIPART_RELATED);
|
||||
|
||||
$dom = new DOMDocument(null, $this->getCharset());
|
||||
@$dom->loadHTML($html);
|
||||
|
||||
$images = $dom->getElementsByTagName('img');
|
||||
|
||||
for ($i = 0; $i < $images->length; $i++) {
|
||||
$img = $images->item($i);
|
||||
$url = $img->getAttribute('src');
|
||||
|
||||
$image_http = new Zend_Http_Client($url);
|
||||
$image_http->setAdapter('Zend_Http_Client_Adapter_Curl');
|
||||
|
||||
$response = $image_http->request();
|
||||
|
||||
if ($response->getStatus() == 200) {
|
||||
$image_content = $response->getBody();
|
||||
|
||||
$pathinfo = pathinfo($url);
|
||||
$mime_type = $response->getHeader('Content-Type');
|
||||
|
||||
$mime = new Zend_Mime_Part($image_content);
|
||||
$mime->id = $url;
|
||||
$mime->location = $url;
|
||||
$mime->type = $mime_type;
|
||||
$mime->disposition = Zend_Mime::DISPOSITION_INLINE;
|
||||
$mime->encoding = Zend_Mime::ENCODING_BASE64;
|
||||
$mime->filename = $pathinfo['basename'];
|
||||
|
||||
$this->addAttachment($mime);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (ZendException $e) {
|
||||
Zend_Registry::get('error_log')->setEventItem('url', $this->getRequest()->getRequestUri())->setEventItem('trace', Zend_Json::encode($e->getTrace()))->setEventItem('params', Zend_Json::encode($this->getRequest()->getParams()))->info($e->getMessage());
|
||||
}
|
||||
|
||||
return parent::setBodyHtml($html, $charset, $encoding);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
class App_Model_Mongo_Adapter
|
||||
{
|
||||
|
||||
const MONGO_DB_ADAPTER_REG_NAME = 'MONGO_DB_ADAPTER_REG_NAME';
|
||||
const MONGO_DB_NAME = 'MONGO_DB_NAME';
|
||||
|
||||
protected $_username = null;
|
||||
protected $_password = null;
|
||||
protected $_host = '127.0.0.1';
|
||||
protected $_port = '27017';
|
||||
|
||||
protected $_connectionUri = null;
|
||||
protected $_dbname = null;
|
||||
|
||||
protected $_mongoClient;
|
||||
|
||||
public function __construct(array $connectionData = array())
|
||||
{
|
||||
//Default Mongo Uri
|
||||
$this->_connectionUri = "mongodb://$this->_host:$this->_port";
|
||||
|
||||
//Autenticazione mongoDB
|
||||
if ($connectionData['user'] && ['password']) {
|
||||
|
||||
$this->_username = $connectionData['user'];
|
||||
$this->_password = $connectionData['password'];
|
||||
|
||||
$this->_host = ($connectionData['host']) ? $connectionData['host'] : $this->_host;
|
||||
$this->_port = ($connectionData['port']) ? $connectionData['port'] : $this->_port;
|
||||
|
||||
$mongoAuth = "$this->_username:$this->_password";
|
||||
$mongoHost = "$this->_host:$this->_port";
|
||||
|
||||
//AuthMongoUri
|
||||
$this->_connectionUri = "mongodb://$mongoAuth@$mongoHost";
|
||||
}
|
||||
|
||||
if($connectionData['dbname']){
|
||||
$this->_dbname = $connectionData['dbname'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \MongoDB\Client
|
||||
*/
|
||||
public function getMongoClient(): \MongoDB\Client
|
||||
{
|
||||
if(!$this->_mongoClient){
|
||||
$this->_mongoClient = new MongoDB\Client($this->_connectionUri);
|
||||
}
|
||||
return $this->_mongoClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDbname(): string
|
||||
{
|
||||
return $this->_dbname;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $dbname
|
||||
*/
|
||||
public function setDbname(string $dbname): void
|
||||
{
|
||||
$this->_dbname = $dbname;
|
||||
Zend_Registry::set(self::MONGO_DB_ADAPTER_REG_NAME,$this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
<?php
|
||||
|
||||
class App_Model_Mongo_Client
|
||||
{
|
||||
|
||||
const WHERE_MONGO_REG_NAME = 'WHERE_MONGO_REG_NAME';
|
||||
|
||||
protected $_config;
|
||||
protected $_mongoClient = null;
|
||||
protected $_db = null;
|
||||
|
||||
public function __construct($connectionUrl = 'mongodb://127.0.0.1:27017')
|
||||
{
|
||||
if (Zend_Registry::isRegistered(App_Model_Mongo_Adapter::MONGO_DB_ADAPTER_REG_NAME)) {
|
||||
$mongoAdapter = Zend_Registry::get(App_Model_Mongo_Adapter::MONGO_DB_ADAPTER_REG_NAME);
|
||||
} else {
|
||||
$mongoAdapter = new App_Model_Mongo_Adapter();
|
||||
$mongoAdapter->setDbname(Zend_Registry::get(App_Model_Mongo_Adapter::MONGO_DB_NAME));
|
||||
}
|
||||
|
||||
$this->_mongoClient = $mongoAdapter->getMongoClient();
|
||||
$dbName = $mongoAdapter->getDbname();
|
||||
|
||||
$this->_db = $this->_mongoClient->selectDatabase($dbName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return App_Model_MongoResource_Abstract
|
||||
* @throws App_Controller_Errors_WebServiceError
|
||||
*/
|
||||
public function getResource($name)
|
||||
{
|
||||
|
||||
if (!isset($this->_resources[$name])) {
|
||||
$class = implode('_', array(
|
||||
'Application',
|
||||
'Model',
|
||||
'MongoResources',
|
||||
ucfirst($name)));
|
||||
|
||||
//Controllo l'esistenza della classe
|
||||
if (!class_exists($class)) {
|
||||
throw new App_Controller_Errors_WebServiceError("Errore generazione la classe risorsa mongo '$class' potrebbe non esistere");
|
||||
}
|
||||
|
||||
$this->_resources[$name] = new $class();
|
||||
}
|
||||
|
||||
return $this->_resources[$name];
|
||||
}
|
||||
|
||||
public function test()
|
||||
{
|
||||
return $this->_mongoClient->test;
|
||||
}
|
||||
|
||||
public function setDatabase($dbName)
|
||||
{
|
||||
return $this->_db = $this->_mongoClient->selectDatabase($dbName);
|
||||
}
|
||||
|
||||
public function listDatabases()
|
||||
{
|
||||
return $this->_mongoClient->listDatabases();
|
||||
}
|
||||
|
||||
public function getDatabase()
|
||||
{
|
||||
return $this->_db;
|
||||
}
|
||||
|
||||
public function deleteDatabase()
|
||||
{
|
||||
return $this->_mongoClient->dropDatabase($this->getDatabase());
|
||||
}
|
||||
|
||||
public function getCollection($resourceName)
|
||||
{
|
||||
$collection = $this->getResource($resourceName)->getCollectionName();
|
||||
return $this->getDatabase()->$collection;
|
||||
}
|
||||
|
||||
public function emptyCollection($resourceName)
|
||||
{
|
||||
return $this->getCollection($resourceName)->deleteMany(['id' => array('$gt'=>0)]);
|
||||
}
|
||||
|
||||
// FUNZIONI PER INTERROGARE IL DB
|
||||
|
||||
public function getById($name, $id)
|
||||
{
|
||||
$optionsParams['projection'] = ['_id' => 0];
|
||||
return $this->getCollection($name)->findOne([$this->getResource($name)->getPrimaryKey() => $id], $optionsParams);
|
||||
}
|
||||
|
||||
public function insert($name, $data)
|
||||
{
|
||||
$id = uniqid();
|
||||
$this->getCollection($name)->insertOne(array_merge([$this->getResource($name)->getPrimaryKey() => $id], $data));
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function update($name, $id, $data)
|
||||
{
|
||||
return $this->getCollection($name)->updateOne([$this->getResource($name)->getPrimaryKey() => $id], ['$set' => $data]);
|
||||
}
|
||||
|
||||
public function delete($name, $id)
|
||||
{
|
||||
return $this->getCollection($name)->deleteOne([$this->getResource($name)->getPrimaryKey() => $id]);
|
||||
}
|
||||
|
||||
public function getCountTotal($name)
|
||||
{
|
||||
return $this->getCollection($name)->countDocuments();
|
||||
}
|
||||
|
||||
public function getCountFilteredTotal($name, $filter)
|
||||
{
|
||||
return $this->getCollection($name)->countDocuments($filter);
|
||||
}
|
||||
|
||||
public function getList($name, $paged = null, $count = null, $where = null, $order = null, $projection = null)
|
||||
{
|
||||
$findParams = array();
|
||||
|
||||
if (null !== $paged && null !== $count && $count > 0 && $paged > 0) {
|
||||
if ($paged > 1) $findParams['skip'] = (($paged - 1) * $count);
|
||||
$findParams['limit'] = $count;
|
||||
}
|
||||
|
||||
$order = (!$order) ? $this->getResource($name)->getDefaultOrder($order) : $order;
|
||||
if ($order && is_array($order)) {
|
||||
$findParams['sort'] = $order;
|
||||
}
|
||||
|
||||
$projection = (!$projection) ? $this->getResource($name)->getDefaultProjection($projection) : $projection;
|
||||
if ($projection && is_array($projection)) {
|
||||
$findParams['projection'] = $projection;
|
||||
}
|
||||
|
||||
if ($where === null) $where = array();
|
||||
|
||||
$cursor = $this->getCollection($name)->find($where, $findParams);
|
||||
|
||||
return $cursor->toArray();
|
||||
}
|
||||
|
||||
public function getListAggregation($name, $paged = null, $count = null, $where = null, $order = null, $projection = null, $addFields = null, $extraAggregation = null)
|
||||
{
|
||||
$aggregations = array();
|
||||
|
||||
if ($where === null) $where = array();
|
||||
if (count($where) > 0) {
|
||||
array_push($aggregations, ['$match' => $where]);
|
||||
}
|
||||
|
||||
$order = $this->getResource($name)->getDefaultOrder($order);
|
||||
if ($order && is_array($order)) {
|
||||
array_push($aggregations, ['$sort' => $order]);
|
||||
}
|
||||
|
||||
if (null !== $paged && null !== $count && $count > 0 && $paged > 0) {
|
||||
if ($paged > 1)
|
||||
array_push($aggregations, ['$skip' => (($paged - 1) * $count)]);
|
||||
array_push($aggregations, ['$limit' => $count]);
|
||||
}
|
||||
|
||||
$projection = $this->getResource($name)->getDefaultProjection($projection);
|
||||
if ($projection && is_array($projection)) {
|
||||
array_push($aggregations, ['$project' => $projection]);
|
||||
}
|
||||
|
||||
//$totElements = $this->getCountTotal($name);
|
||||
$addFields = $this->getResource($name)->getDefaultAddFields();
|
||||
if ($addFields && is_array($addFields)) {
|
||||
|
||||
/*if($totElements <= 0){
|
||||
unset($addFields['Data']);
|
||||
}*/
|
||||
|
||||
array_push($aggregations, ['$addFields' => $addFields]);
|
||||
}
|
||||
|
||||
if ($extraAggregation && is_array($extraAggregation)) {
|
||||
if(count($extraAggregation) > 1){
|
||||
$aggregations = array_merge($aggregations, $extraAggregation);
|
||||
}else{
|
||||
array_push($aggregations, $extraAggregation);
|
||||
}
|
||||
}
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($aggregations,true));
|
||||
|
||||
$cursor = $this->getCollection($name)->aggregate($aggregations);
|
||||
|
||||
return $cursor->toArray();
|
||||
}
|
||||
|
||||
public function getByColumnName($name, $columnName, $value, $op = "=", $all = false)
|
||||
{
|
||||
|
||||
switch ($op) {
|
||||
case'=':
|
||||
default:
|
||||
$params = array($columnName => $value);
|
||||
break;
|
||||
case 'LIKE':
|
||||
$params = array($columnName => ['$regex' => $value, '$options' => 'i']);
|
||||
break;
|
||||
}
|
||||
|
||||
if ($all) {
|
||||
return $this->getCollection($name)->find($params)->toArray();
|
||||
} else {
|
||||
return $this->getCollection($name)->findOne($params);
|
||||
}
|
||||
}
|
||||
|
||||
public function find($name, $params = array())
|
||||
{
|
||||
return $this->getCollection($name)->find($params)->toArray();
|
||||
}
|
||||
|
||||
public function aggregate($name, $aggregate)
|
||||
{
|
||||
return $this->getCollection($name)->aggregate($aggregate);
|
||||
}
|
||||
|
||||
// CRUD FUNCTION WITH OBJECTID
|
||||
|
||||
public function getByObjectId($name, $id)
|
||||
{
|
||||
return $this->getCollection($name)->find([$this->getResource($name)->getPrimaryKey() => new MongoDB\BSON\ObjectID($id)])->toArray();
|
||||
}
|
||||
|
||||
public function insertWithObjectId($name, $data)
|
||||
{
|
||||
unset($data['_id']);
|
||||
return $this->getCollection($name)->insertOne($data);
|
||||
}
|
||||
|
||||
public function updateByObjectId($name, $id, $data)
|
||||
{
|
||||
return $this->getCollection($name)->updateOne([$this->getResource($name)->getPrimaryKey() => new MongoDB\BSON\ObjectID($id)], ['$set' => $data]);
|
||||
}
|
||||
|
||||
public function deleteByObjectId($name, $id)
|
||||
{
|
||||
return $this->getCollection($name)->deleteOne([$this->getResource($name)->getPrimaryKey() => new MongoDB\BSON\ObjectID($id)]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @see Zend_Paginator_Adapter_Interface
|
||||
*/
|
||||
require_once 'Zend/Paginator/Adapter/Interface.php';
|
||||
|
||||
class App_Model_Mongo_PaginatorAdapter implements Zend_Paginator_Adapter_Interface
|
||||
{
|
||||
|
||||
protected $_cursor = null;
|
||||
|
||||
|
||||
public function __construct(MongoDB\Driver\Cursor $cursor)
|
||||
{
|
||||
$this->_cursor = $cursor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an cursor limited to items for a page.
|
||||
*
|
||||
* @param integer $offset Page offset
|
||||
* @param integer $itemCountPerPage Number of items per page
|
||||
* @return MongoDB\Driver\Cursor
|
||||
*/
|
||||
public function getItems($offset, $itemCountPerPage)
|
||||
{
|
||||
$cursor = $this->_cursor->skip($offset)->limit($itemCountPerPage);
|
||||
return $cursor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the total number of rows in the cursor.
|
||||
*
|
||||
* @return integer
|
||||
*/
|
||||
public function count()
|
||||
{
|
||||
return count($this->_cursor->toArray());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
|
||||
class App_Model_MongoResource_Abstract extends Zend_Db_Table_Abstract
|
||||
{
|
||||
|
||||
protected $_defaultOrder; // Formato classico '<NOMECAMPO> <DESC | ASC>'
|
||||
protected $_defaultTipoOrder;
|
||||
|
||||
public $_defaultProjection; // array di projection mongo db
|
||||
public $_defaultAddFields; // array di addFileds con el regole di mongoDb
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
if(!$this->_defaultOrder){
|
||||
throw new App_Controller_Errors_WebServiceError("'_defaultOrder' non definito per la risorsa ". get_class($this));
|
||||
}
|
||||
|
||||
if(!$this->_defaultTipoOrder){
|
||||
throw new App_Controller_Errors_WebServiceError("'_defaultTipoOrder' non definito per la risorsa " . get_class($this));
|
||||
}
|
||||
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
//Funzione che restituisce il nome della collezione
|
||||
public function getCollectionName()
|
||||
{
|
||||
return $this->_name;
|
||||
}
|
||||
|
||||
//Funzione che restituisce la chiave primaria sicura
|
||||
public function getPrimaryKey()
|
||||
{
|
||||
if (is_array($this->_primary)) return $this->_primary[1];
|
||||
return $this->_primary;
|
||||
}
|
||||
|
||||
//Funzione che restituisce il campo ordinamento di default
|
||||
public function getDefaultOrder($order)
|
||||
{
|
||||
$order = (!$order) ? $this->_defaultOrder : $order;
|
||||
|
||||
if (!is_array($order)) {
|
||||
$order = explode(',', $order);
|
||||
}
|
||||
|
||||
$sort = array();
|
||||
if (count($order) > 0)
|
||||
foreach ($order as $val) {
|
||||
$tmp = explode(' ', trim($val));
|
||||
$orderType = strtoupper(trim($tmp[1]));
|
||||
$orderType = ($tmp[1] && ($orderType == 'ASC' || $orderType == 'DESC')) ? $orderType : 'ASC';
|
||||
$sort[trim($tmp[0])] = ($orderType == 'ASC') ? 1 : -1;
|
||||
}
|
||||
return $sort;
|
||||
}
|
||||
|
||||
//Funzione che restituisce il tipo di ordinamento di default
|
||||
public function getDefaultTipoOrder()
|
||||
{
|
||||
if (isset($this->_defaultTipoOrder) && $this->_defaultTipoOrder) return $this->_defaultTipoOrder;
|
||||
return "ASC";
|
||||
}
|
||||
|
||||
public function getDefaultAddFields()
|
||||
{
|
||||
if($this->_defaultAddFields) return $this->_defaultAddFields;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getDefaultProjection($projection, $defaultProjection = null, $hideObjectId = true)
|
||||
{
|
||||
$defaultProjection = ($this->_defaultProjection === null) ? (($hideObjectId) ? ['_id'=>0] : []) : $this->_defaultProjection;
|
||||
$projectionArray = ($hideObjectId) ? ['_id'=>0] : [];
|
||||
|
||||
if (is_null($projection) || $projection === '*' || (is_array($projection) && count($projection) <= 0)) {
|
||||
return $defaultProjection;
|
||||
}
|
||||
|
||||
if (is_string($projection)) {
|
||||
$projection = explode(',', $projection);
|
||||
}
|
||||
|
||||
// aggiungendo '#0' tra i valori della proiezione eseguo la proiezione negativa
|
||||
$projectionType = in_array('#0', $projection) ? 0 : 1;
|
||||
|
||||
if (is_array($projection) && count($projection) > 0) {
|
||||
foreach ($projection as $column) {
|
||||
$projectionArray[$column] = $projectionType;
|
||||
}
|
||||
}
|
||||
|
||||
return $projectionArray;
|
||||
}
|
||||
|
||||
public function getDefaultOrderString()
|
||||
{
|
||||
return $this->getDefaultOrder() . ' ' . $this->getDefaultTipoOrder();
|
||||
}
|
||||
|
||||
//--------------- FUNZIONI PER LA GESTIONE DI DATABASE MULTIPLI ------------------------------------------
|
||||
|
||||
public function _setDbName($nomedb)
|
||||
{
|
||||
Zend_Registry::set(App_Model_Mongo_Adapter::MONGO_DB_NAME, $nomedb);
|
||||
}
|
||||
|
||||
public function getDbName()
|
||||
{
|
||||
return Zend_Registry::get(App_Model_Mongo_Adapter::MONGO_DB_NAME);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class App_Model_Resource_Abstract
|
||||
*/
|
||||
class App_Model_Resource_Abstract extends Zend_Db_Table_Abstract
|
||||
{
|
||||
|
||||
protected $_defaultOrder; // [obbligatorio]
|
||||
protected $_defaultTipoOrder; // [obbligatorio]
|
||||
protected $_defaultSelectColumns; // [opzionale]
|
||||
protected $_defaultJoinData; // [opzionale] può essere un array singolo o multiplo per applicare più join insieme
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
if(!$this->_defaultOrder){
|
||||
throw new App_Controller_Errors_WebServiceError("'_defaultOrder' non definito per la risorsa ". get_class($this));
|
||||
}
|
||||
|
||||
if(!$this->_defaultTipoOrder){
|
||||
throw new App_Controller_Errors_WebServiceError("'_defaultTipoOrder' non definito per la risorsa " . get_class($this));
|
||||
}
|
||||
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
//Funzione che restituisce il nome della tabella
|
||||
public function getTableName()
|
||||
{
|
||||
return $this->_name;
|
||||
}
|
||||
|
||||
//Funzione che restituisce la chiave primaria sicura
|
||||
public function getPrimaryKey()
|
||||
{
|
||||
if (is_array($this->_primary)) return $this->_primary[1];
|
||||
return $this->_primary;
|
||||
}
|
||||
|
||||
//Funzione che restituisce il campo ordinamento di default
|
||||
public function getDefaultOrder()
|
||||
{
|
||||
if (isset($this->_defaultOrder) && $this->_defaultOrder) return $this->_defaultOrder;
|
||||
return $this->getPrimaryKey();
|
||||
}
|
||||
|
||||
//Funzione che restituisce il tipo di ordinamento di default
|
||||
public function getDefaultTipoOrder()
|
||||
{
|
||||
if (isset($this->_defaultTipoOrder) && $this->_defaultTipoOrder) return $this->_defaultTipoOrder;
|
||||
return "ASC";
|
||||
}
|
||||
|
||||
//Funzione che restituisce il tipo di select default
|
||||
public function getDefaultSelectColumns()
|
||||
{
|
||||
if (isset($this->_defaultSelectColumns) && $this->_defaultSelectColumns) return $this->_defaultSelectColumns;
|
||||
return "*";
|
||||
}
|
||||
|
||||
//Funzione che restituisce il campo joinData di default
|
||||
public function getDefaultJoinData()
|
||||
{
|
||||
if (isset($this->_defaultJoinData) && $this->_defaultJoinData) return $this->_defaultJoinData;
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getDefaultOrderString()
|
||||
{
|
||||
return $this->getDefaultOrder() . ' ' . $this->getDefaultTipoOrder();
|
||||
}
|
||||
|
||||
//--------------- FUNZIONI PER LA GESTIONE DI DATABASE MULTIPLI ------------------------------------------
|
||||
|
||||
public function _setDbName($nomedb)
|
||||
{
|
||||
$dbparam = $this->_db->getConfig();
|
||||
$dbparam['dbname'] = $nomedb;
|
||||
$this->_db = Zend_Db::factory('Pdo_Mysql', $dbparam);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Zend_Db_Adapter_Abstract
|
||||
*/
|
||||
public function getDbAdapter()
|
||||
{
|
||||
return $this->_db;
|
||||
}
|
||||
|
||||
public function setDBConnection($nomeDB)
|
||||
{
|
||||
$this->_db->query('USE ' . $nomeDB);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
class App_Model_RestResource_Abstract
|
||||
{
|
||||
|
||||
const METHOD_BY_ID = 1;
|
||||
const METHOD_ALL_LIST = 2;
|
||||
const METHOD_FILTER = 3;
|
||||
const METHOD_GENERIC = 4;
|
||||
const METHOD_BY_COLUMNNAME = 5;
|
||||
const METHOD_CUSTOM_URL = 6;
|
||||
|
||||
protected $_apiUrl;
|
||||
protected $_apiVersion = "v1";
|
||||
protected $_secretId = false;
|
||||
protected $_testHeader = false;
|
||||
|
||||
protected $_httpClient = null;
|
||||
protected $_risorsa;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
|
||||
if (!$this->_risorsa || !$this->_apiUrl || !$this->_apiVersion)
|
||||
throw new Exception("Non sono stati specificati tutti i parametri necessari alla risorsa (_risorsa,_apiUrl,_apiVersion)");
|
||||
|
||||
if ($this->_httpClient instanceof Zend_Http_Client) {
|
||||
//$this->_httpClient = $this->_httpClient;
|
||||
} else {
|
||||
$this->_httpClient = new Zend_Http_Client();
|
||||
$this->_httpClient->setConfig(array(
|
||||
'adapter' => 'Zend_Http_Client_Adapter_Curl',
|
||||
'maxredirects' => 0,
|
||||
'timeout' => 60,
|
||||
'ssltransport' => 'ssl'
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/***** METODI COMUNI DELLE CHIMATE *****/
|
||||
|
||||
public function postCall($dati)
|
||||
{
|
||||
$this->_httpClient->setMethod('POST');
|
||||
$this->_httpClient->setUri($this->getBaseUrl());
|
||||
$this->_httpClient->setRawData(json_encode($dati), 'application/json;charset=utf-8');
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function updateById($id, $item)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('PUT');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_BY_ID, array('id' => $id)));
|
||||
$this->_httpClient->setRawData(json_encode($item), 'application/json;charset=utf-8');
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function deleteById($id)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('DELETE');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_BY_ID, array('id' => $id)));
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getById($id)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_BY_ID, array('id' => $id)));
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getByColumnName($column, $value)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_BY_COLUMNNAME, array('colname' => $column, 'value' => $value)));
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getList($paged = null, $count = null, $order = null)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_ALL_LIST));
|
||||
$this->_httpClient->setParameterGet(array('page' => $paged, 'count' => $count, 'order' => $order));
|
||||
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getFiltered($paged = null, $count = null, $order = null, $where = null)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
|
||||
if (is_array($order)) {
|
||||
$orderStr = "";
|
||||
$last_key = key(array_slice($order, -1, 1, TRUE));
|
||||
foreach ($order as $k => $val) {
|
||||
$orderStr .= $val;
|
||||
if ($k !== $last_key) $orderStr .= ",";
|
||||
}
|
||||
}
|
||||
if ($orderStr) $order = $orderStr;
|
||||
|
||||
$this->_httpClient->setParameterGet(array('page' => $paged, 'count' => $count, 'order' => $order));
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_FILTER, $where));
|
||||
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getByMethod($method, $params = null)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_GENERIC, $method));
|
||||
$this->_httpClient->setParameterGet($params);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getByCustomUrl($url, $params = null)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_CUSTOM_URL, $url));
|
||||
$this->_httpClient->setParameterGet($params);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function postByCustomUrl($url, $dati = null)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('POST');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_CUSTOM_URL, $url));
|
||||
$this->_httpClient->setRawData(json_encode($dati), 'application/json;charset=utf-8');
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
/***** METODI PRIVATI PER GESTIRE LE CHIAMATE *****/
|
||||
|
||||
private function getMethodUrl($method, $params = null)
|
||||
{
|
||||
$url = $this->getBaseUrl(!(self::METHOD_CUSTOM_URL === $method));
|
||||
switch ($method) {
|
||||
case self::METHOD_BY_ID:
|
||||
if (!isset($params['id'])) throw new Exception("Id Richiesto");
|
||||
$url .= "/" . $params['id'];
|
||||
break;
|
||||
case self::METHOD_ALL_LIST:
|
||||
break;
|
||||
case self::METHOD_FILTER:
|
||||
$url .= "/method/filtra";
|
||||
$this->_httpClient->setParameterGet($params);
|
||||
break;
|
||||
case self::METHOD_GENERIC:
|
||||
if (!$params) throw new Exception("Nome del metodo non valido");
|
||||
$url .= "/method/$params";
|
||||
break;
|
||||
case self::METHOD_BY_COLUMNNAME:
|
||||
if (!isset($params['colname'])) throw new Exception("Nome Colonna Richiesto");
|
||||
if (!isset($params['value'])) throw new Exception("Valore Richiesto");
|
||||
$url .= "/method/bycolumn/colname/" . $params['colname'] . "/val/" . $params['value'];
|
||||
break;
|
||||
case self::METHOD_CUSTOM_URL:
|
||||
if (!$params) throw new Exception("Nome dell'url non valido");
|
||||
$url .= "$params";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return $url;
|
||||
}
|
||||
|
||||
private function getBaseUrl($withResouces = true)
|
||||
{
|
||||
if ($withResouces) {
|
||||
return $this->_apiUrl . "/" . $this->_apiVersion . "/" . strtolower($this->_risorsa);
|
||||
} else {
|
||||
return $this->_apiUrl . "/" . $this->_apiVersion;
|
||||
}
|
||||
}
|
||||
|
||||
private function executeCall()
|
||||
{
|
||||
|
||||
if ($this->_secretId) {
|
||||
$this->_httpClient->setHeaders('Authorization', $this->_secretId);
|
||||
}
|
||||
|
||||
if ($this->_testHeader) {
|
||||
$this->_httpClient->setHeaders('X-As-Dev-On', '1');
|
||||
}
|
||||
|
||||
$httpResponse = $this->_httpClient->request();
|
||||
|
||||
//Zend_Registry::get('log')->info(print_r($this->_httpClient->getLastRequest(),true));
|
||||
//Zend_Registry::get('log')->info(print_r($httpResponse,true));
|
||||
|
||||
$httpResponseEncoded = json_decode($httpResponse->getBody(), 1);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore codifica JSON:");
|
||||
Zend_Registry::get('log')->info(print_r($httpResponse, true));
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->_httpClient->getLastResponse()->getStatus() != '200') {
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore status response " . $this->_httpClient->getLastResponse()->getStatus());
|
||||
Zend_Registry::get('log')->info(print_r($httpResponseEncoded, true));
|
||||
throw new App_Exception_ResponseCloudException($httpResponseEncoded['message'], $httpResponseEncoded['errorCode']);
|
||||
}
|
||||
|
||||
return $httpResponseEncoded;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user