When I call endpoint from flash all the action is done well but the response is empty. The code is:
class AmfController extends Zend_Controller_Action {
public function indexAction()
{
$server = new Zend_Amf_Server();
$server->setProduction(false);
$server->setClass('Application_Model_Amf');
$response = $server->handle();
echo $response;
}
}
and
class Application_Model_Amf {
/**
*
* #param bytearray $data
* #param string $dateString
* #return int
*/
public function save($data, $dateString)
{
$dateString = str_replace(array('|', ':'), array('_', ''), $dateString);
//file_put_contents("$dateString.jpg", $data);
$r = new stdClass();
$r->error = 0;
return $r;
}
}
I also tried
public function save($data, $dateString)
{
$dateString = str_replace(array('|', ':'), array('_', ''), $dateString);
//file_put_contents("$dateString.jpg", $data);
return true;
}
but it worked neither - still empty response. How can I return response like this stdClass() ? Or only integer value 1 or 0?
The solution is to add die()
public function indexAction()
{
$server = new Zend_Amf_Server();
$server->setProduction(false);
$server->setClass('Application_Model_Amf');
$response = $server->handle();
echo $response;
die();
}
Related
In my Laravel application, I need submodels of the base ORM model, for specific types of item in my DB which is specified in 'type' column in database.
In my base model, I use this override for function newFromBuilder
// OVERRIDES
public function newFromBuilder($attributes = [], $connection = null)
{
$class = "\\App\\Models\\" . ucfirst($attributes->type);
if (class_exists($class)) {
$model = new $class();
} else {
$model = $this->newInstance([], true);
}
$model->setRawAttributes((array)$attributes, true);
$model->setConnection($connection ?: $this->getConnectionName());
$model->fireModelEvent('retrieved', false);
return $model;
}
but for some reason when i call save or update function in submodel nothing happen :( Each submodel should ingered save function of fase model s that right ? Could anybody help me to fix issue with save function ?
Base model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use App\Models\Devices;
use App\Models\Records;
use App\Models\Rooms;
use App\Helpers\SettingManager;
use App\Types\GraphPeriod;
use App\Types\PropertyType;
class Properties extends Model
{
protected $fillable = [];
protected $table = 'sh_properties';
protected $primaryKey = 'id';
public $period = GraphPeriod::DAY;
//OVERIDES
public function newFromBuilder($attributes = [], $connection = null)
{
$class = "\\App\\Models\\" . ucfirst($attributes->type);
if (class_exists($class)) {
$model = new $class();
} else {
$model = $this->newInstance([], true);
}
$model->setRawAttributes((array)$attributes, true);
$model->setConnection($connection ?: $this->getConnectionName());
$model->fireModelEvent('retrieved', false);
return $model;
}
//NEW RELATIONS
public function records()
{
return $this->hasMany(Records::class, 'property_id');
}
public function latestRecord()
{
return $this->hasOne(Records::class, 'property_id')->latestOfMany();
}
public function device()
{
return $this->belongsTo(Devices::class);
}
public function room()
{
return $this->belongsTo(Rooms::class);
}
public function settings()
{
if ($settings = SettingManager::getGroup('property-' . $this->id)) {
return $settings;
}
return false;
}
//FUNCTIONS
public function getLatestRecordNotNull()
{
return Records::where("property_id", $this->id)->where("value", "!=", null)->where("value", "!=", 0)->first();
}
//Virtual Values
use HasFactory;
//Add Function for mutator for vaue (vith units) and rav value
public function values()
{
$dateFrom = Carbon::now()->subDays(1);
switch ($this->period) {
case GraphPeriod::WEEK:
$dateFrom = Carbon::now()->subWeek(1);
break;
case GraphPeriod::MONTH:
$dateFrom = Carbon::now()->subMonth(1);
break;
case GraphPeriod::YEAR:
$dateFrom = Carbon::now()->subYear(1);
break;
}
return $this->hasMany(Records::class, 'property_id')->whereDate('created_at', '>', $dateFrom)->orderBy('created_at', 'DESC');
}
public function getAgregatedValuesAttribute($period = GraphPeriod::DAY)
{
$dateFrom = Carbon::now()->subDays(1);
$periodFormat = "%Y-%m-%d %hh";
switch ($this->period) {
case GraphPeriod::WEEK:
$dateFrom = Carbon::now()->subWeek(1);
$periodFormat = "%Y-%m-%d";
break;
case GraphPeriod::MONTH:
$dateFrom = Carbon::now()->subMonth(1);
$periodFormat = "%Y-%m-%d";
break;
case GraphPeriod::YEAR:
$dateFrom = Carbon::now()->subYear(1);
$periodFormat = "%Y-%m";
break;
}
$agregatedData = Records::select(['value', 'done', 'created_at'])
->selectRaw("DATE_FORMAT(created_at, ?) as period", [$periodFormat])
->selectRaw("ROUND(MIN(value), 1) AS min")
->selectRaw("ROUND(MAX(value), 1) AS max")
->selectRaw("ROUND(AVG(value), 1) AS value")
->where('property_id', $this->id)
->orderBy('created_at', 'DESC')
->groupBy('period');
$agregatedData->where('created_at', '>=', $dateFrom);
return $agregatedData->get();
}
public function last_value()
{
return $this->hasOne(Records::class, 'property_id', 'id')->latest();
}
//Virtual Values
//Virtual Values
/**
* Minimum value that property had in past.
*
* #return int
*/
public function getMaxValueAttribute()
{
if ($this->records) {
return $this->records->max("value");
}
return false;
}
/**
* Maximum value that property had in past.
*
* #return int
*/
public function getMinValueAttribute()
{
if ($this->records) {
return $this->records->min("value");
}
return false;
}
/**
* step value used to increment each value usually used for range type or thermostats, graphs also.
*
* #return int
*/
public function getStepValueAttribute()
{
if ($step = SettingManager::get('step', 'property-' . $this->id)) {
return ($step->value < 1 ? $step->value : 1);
}
return false;
}
/**
* max set value for prop
*
* #return int
*/
public function getMaxValueSettingAttribute()
{
if ($step = SettingManager::get('max', 'property-' . $this->id)) {
return ($step->value > 1 ? $step->value : 1);
}
return false;
}
/**
* min set value for prop
*
* #return int
*/
public function getMinValueSettingAttribute()
{
if ($step = SettingManager::get('min', 'property-' . $this->id)) {
return ($step->value > 1 ? $step->value : 1);
}
return false;
}
public function setValue($value)
{
$record = new Records;
$record->value = $value;
$record->property_id = $this->id;
$record->save();
return true;
}
}
Submodel
namespace App\Models;
use App\Models\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Humi extends Properties
{
protected $historyDefault = 90;
protected $unitsDefault = "%";
protected $iconDefault = "";
public function save(array $options = [])
{
// before save code
$result = parent::save($options); // returns boolean
// after save code
return $result; // do not ignore it eloquent calculates this value and returns this, not just to ignore
}
}
Thank you in advance for any suggestions or help :)
When a new instance is created with the $this->newInstance() function, the $model->exists property is set to true. I think you should do the same in your if statement as well. Otherwise it will try to create a new record in the database.
It might be a good idea to copy the rest of the function as well to avoid any other problems it may cause.
if (class_exists($class)) {
$model = new $class();
// Important
$model->exists = true;
$model->setTable($this->getTable());
$model->mergeCasts($this->casts);
} else {
$model = $this->newInstance([], true);
}
Laravel 7.x
I need to access the timezone from where the application was accessed. I am only getting UTC in return from echo date_default_timezone_get();.
But I need to get something like Asia/Kolkata in return. For the access logs.
As said in the comments, you can only make a guess, but not have 100% sure.
I made some modifications to Chandra Nakka's function.
It will validate the guess with the timezone_identifiers_list() function, if it's not a valid timezone, the default will be returned.
function set_timezone_by_client_location($ip = NULL, $deep_detect = TRUE) {
$output = NULL;
if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
$ip = $_SERVER["REMOTE_ADDR"];
if ($deep_detect) {
if (filter_var(#$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
if (filter_var(#$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
}
$continents = array(
"AF" => "Africa",
"AN" => "Antarctica",
"AS" => "Asia",
"EU" => "Europe",
"OC" => "Australia",
"NA" => "America",
"SA" => "America"
);
$timezone = null;
if (filter_var($ip, FILTER_VALIDATE_IP)) {
$ipdat = #json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
if (#strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
$timezone = #$continents[strtoupper($ipdat->geoplugin_continentCode)] . '/' . #$ipdat->geoplugin_regionName;
$timezone = str_replace(' ', '_', $timezone);
}
}
if(!in_array($timezone, timezone_identifiers_list())){
$timezone = date_default_timezone_get();
}
return $timezone;
}
$timezone = set_timezone_by_client_location();
echo $timezone;
Framework: Laravel 7.x
namespace App\Services;
class TimeZoneService
{
/**
* Protected Variables
*/
protected $host = null;
protected $filter = null;
protected $ip = null;
protected $json = null;
public function __construct($ip, $filter = false)
{
$this->ip = $ip;
$this->filter = $filter;
$this->host = "http://www.geoplugin.net/json.gp?ip={$ip}";
}
/**
* fetch the location data via given IP address
*
* #return array
*/
public function getData()
{
if(function_exists('curl_init'))
{
# use cURL to fetch data
$request = curl_init();
# setting options
curl_setopt($request, CURLOPT_URL, $this->host);
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($request, CURLOPT_USERAGENT, 'geoPlugin PHP Class v1.1');
# response
$this->json = curl_exec($request);
# closing cURL
curl_close($request);
}
else if (ini_get('allow_url_fopen'))
{
# fall back to fopen()
$this->json = file_get_contents($this->host, 'r');
}
else
{
trigger_error('geoPlugin Error: Cannot retrieve data.', E_USER_ERROR);
return;
}
# returning
return $this;
}
/**
* convert the json string to php array
* based on the filter property
*
* #return array
*/
public function toArray()
{
# condition(s)
if($this->filter != true)
{
return json_decode($this->json, true);
}
# filtering & returning
return $this->__filter();
}
/**
* convert the json string to php object
* based on the filter property
*
* #return object
*/
public function toObject()
{
# condition(s)
if($this->filter != true)
{
return json_decode($this->json);
}
# filtering & returning
return (object)$this->__filter();
}
/**
* return collected location data in the form of json
* based on the filter property
*
* #return string
*/
public function toJson()
{
# condition(s)
if($this->filter != true)
{
return $this->json;
}
# filtering & returning
return json_encode($this->__filter());
}
/**
* filter the object keys
*
* #return array
*/
private function __filter()
{
# applying filter
foreach(json_decode($this->json, true) as $key => $item)
{
$return[str_replace('geoplugin_', '', $key)] = $item;
}
# returning
return $return;
}
}
SomeController.php
/**
* Services
*/
use App\Services\TimeZoneService;
class SomeController extends Controller
{
public function someMethod()
{
# services
$TimeZone = new TimeZoneService(<string IP_ADDRESS>, <boolean FILTER>);
$locationData = $TimeZone->getData()->toJson();
# OR
$locationData = $TimeZone->getData()->toArray();
# OR
$locationData = $TimeZone->getData()->toObject();
...
}
}
This code is working fine for me. However, If you see any room for improvement then please feel free to update the code to help others.
Thank you.
I have trouble defining my datetime param with Symfony.
I am trying to return null if last_scan_date is null
and if not to return results!
Error says:
Argument 2 passed to checkLastScan() must be an instance of DateTime, string given
My function:
public function checkLastScan($hash, \DateTime $lastScanDate)
{
$findLastScan = $this->getMyRepository()->findOneBy([
'hash' => $hash,
'lastScanDate' => $lastScanDate
]);
if (!$findLastScan) {
throw new \Exception('Not found!');
}
if ($lastScanDate === null) {
return null;
} else {
return $findLastScan;
}
}
and my call:
$this->requirePostParams(['hash', 'last_scan_date']);
$this->container->get('app')->checkLastScan(
$this->data['hash'],
$this->data['last_scan_date']
);
return $this->success();
And enitity:
/**
* #ORM\Column(name="last_scan_date", type="date", nullable=true)
*/
private $lastScanDate;
Maybe problem is when requiring post params like:
/**
* Require post params
*
* #param $params
*/
protected function requirePostParams($params)
{
$currentRequest = $this->get('request_stack')->getCurrentRequest();
$postData = $currentRequest->request->all();
$postContent = json_decode($currentRequest->getContent(), true);
if (!empty($postContent)) {
$postData = $postContent;
}
$this->data = $postData;
$missingParams = [];
foreach ($params as $param) {
if (!array_key_exists($param, $postData)) {
$missingParams[] = $param;
}
}
If $this->data (I asked at first but you did not answer to me properly) is just the POST array, of course all members of the array are treated as string.
You have to parse last_scan_date string and transform it to DateTime type.
Here is the code of the function (change the value of YOUR_POST_FORMAT to the format you use in your HTML form):
/**
* Require post params
*
* #param $params
*/
protected function requirePostParams($params)
{
$currentRequest = $this->get('request_stack')->getCurrentRequest();
$postData = $currentRequest->request->all();
$postContent = json_decode($currentRequest->getContent(), true);
if (!empty($postContent)) {
$postData = $postContent;
}
// HERE YOU PARSE STRING TO DATETIME TYPE
if (isset($postData['last_scan_date']) && !empty($postData['last_scan_date'])) {
$postData['last_scan_date'] = DateTime::createFromFormat('YOUR POST FORMAT', $postData['last_scan_date'])
} else {
$postData['last_scan_date'] = null;
}
$this->data = $postData;
$missingParams = [];
foreach ($params as $param) {
if (!array_key_exists($param, $postData)) {
$missingParams[] = $param;
}
}
}
I've made a website in symfony. This website contains some forms with a checkbox choice and other fields.
The datas from the checkbox are serialized on flush.
It's all good.
Now i have to export this datas and i use the data exporter library from Sonata project. But the datas are still serialized and i have some things like that in my csv file:
a:2:{i:0;s:6:"Volets";i:1;s:22:"Panneau de remplissage";}
How can I unserialize my datas in order to have a clean csv file?
Here's my code
My controller
/**
* #Security("has_role('ROLE_WEBFORM')")
*/
public function exportAction(Request $request)
{
$filters = array();
$this->handleFilterForm($request, $filters);
if (!$filters['webform']) {
throw $this->createNotFoundException();
}
$webForm = $this->getRepository('CoreBundle:WebForm')->find($filters['webform']);
$source = new WebFormEntryIterator($webForm, $this->getEntityManager(), $this->get('ines_core.embedded_form.field_type_registry'), $filters);
return WebFormEntryExporter::createResponse('export.csv', $source);
}
and my class WebFormEntryExporter
class WebFormEntryExporter
{
public static function createResponse($filename, SourceIteratorInterface $source)
{
$writer = new CsvWriter('php://output', ';', '"', "", true, true);
$contentType = 'text/csv';
$callback = function() use ($source, $writer) {
$handler = \Exporter\Handler::create($source, $writer);
$handler->export();
};
return new StreamedResponse($callback, 200, [
'Content-Type' => $contentType,
'Content-Disposition' => sprintf('attachment; filename=%s', $filename)
]);
}
}
And my WebFormEntryIterator
class WebFormEntryIterator implements SourceIteratorInterface
{
protected $em;
protected $registry;
protected $repository;
protected $query;
protected $webForm;
protected $iterator;
public function __construct(WebForm $webForm, EntityManager $em, FieldTypeRegistry $registry, array $filters)
{
$this->webForm = $webForm;
$this->em = $em;
$this->registry = $registry;
$this->initQuery($filters);
}
/**
* {#inheritdoc}
*/
public function current()
{
$current = $this->iterator->current();
$entity = $current[0];
$data = [];
$data['ID'] = $entity->getId();
$data['Formulaire'] = $this->webForm->getName();
$data['Date de création'] = date_format($entity->getCreatedAt(), 'd/m/Y H:i:s');
foreach ($this->webForm->getEmbeddedFieldConfigs() as $fieldConfig) {
$header = $fieldConfig->getLabel();
$meta = $entity->getContentMeta($fieldConfig->getName());
$extension = $this->registry->get($meta->getFormat());
if (method_exists($extension, 'setEntityManager')) {
$extension->setEntityManager($this->em);
}
$value = $extension->formatMeta($meta);
$data[$header] = $value;
unset($extension);
}
$this->query->getEntityManager()->getUnitOfWork()->detach($current[0]);
unset($entity);
unset($webForm);
return $data;
}
/**
* {#inheritdoc}
*/
public function next()
{
$this->iterator->next();
}
/**
* {#inheritdoc}
*/
public function key()
{
return $this->iterator->key();
}
/**
* {#inheritdoc}
*/
public function valid()
{
return $this->iterator->valid();
}
/**
* {#inheritdoc}
*/
public function rewind()
{
if ($this->iterator) {
throw new InvalidMethodCallException('Cannot rewind a Doctrine\ORM\Query');
}
$this->iterator = $this->query->iterate();
$this->iterator->rewind();
}
protected function initQuery(array $filters)
{
$repository = $this->em->getRepository('InesCoreBundle:Content');
$qb = $repository->getWebFormEntryQueryBuilder();
$repository->applyWfeFilters($qb, $filters);
$this->query = $qb->getQuery();
}
}
Sorry for my broken English.
Thanks a lot
thanks chalasr.
I have to make the tratment in this file, in the current() function.
This is what I've done:
public function current()
{
$current = $this->iterator->current();
$entity = $current[0];
$data = [];
$data['ID'] = $entity->getId();
$data['Formulaire'] = $this->webForm->getName();
$data['Date de création'] = date_format($entity->getCreatedAt(), 'd/m/Y H:i:s');
foreach ($this->webForm->getEmbeddedFieldConfigs() as $fieldConfig) {
$header = $fieldConfig->getLabel();
$meta = $entity->getContentMeta($fieldConfig->getName());
$extension = $this->registry->get($meta->getFormat());
if (method_exists($extension, 'setEntityManager')) {
$extension->setEntityManager($this->em);
}
$value = $extension->formatMeta($meta);
if($this->is_serialized($value)) {
$value = unserialize($value);
$data[$header] = implode(' | ', $value);
} else {
$data[$header] = $value;
}
unset($extension);
}
$this->query->getEntityManager()->getUnitOfWork()->detach($current[0]);
unset($entity);
unset($webForm);
return $data;
}
public function is_serialized($data)
{
if (trim($data) == "") { return false; }
if (preg_match("/^(i|s|a|o|d){1}:{1}(.*)/si",$data)) { return true; }
return false;
}
I'm working on a Joomla 3 component. Currently I'm programming the backend. I'm having a form to add new data and it is working quite well. But when I want to update the data the component creates a new item instead of updating the existing.
I was searching for position which let Joomla know, that this is an update, but without success.
So my question: what is the information that makes Joomla updating the data?
My Code:
Table:ia.php
class mkTableia extends JTable
{
/**
* Constructor
*
* #param object Database connector object
*/
function __construct(&$db)
{
parent::__construct('#__tbl_ia', 'ID', $db);
}
}
Model: ia.php
class mkModelia extends JModelAdmin
{
public function getTable($type = 'ia', $prefix = 'mkTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_mk.ia', 'ia',
array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
}
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_mk.edit.ia.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
}
View:view.html.php
class mkViewia extends JViewLegacy
{
/**
* display method of Hello view
* #return void
*/
public function display($tpl = null)
{
// get the Data
$form = $this->get('Form');
$item = $this->get('Item');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
// Assign the Data
$this->form = $form;
$this->item = $item;
// Set the toolbar
$this->addToolBar();
// Display the template
parent::display($tpl);
}
/**
* Setting the toolbar
*/
protected function addToolBar()
{
$input = JFactory::getApplication()->input;
$input->set('hidemainmenu', true);
$isNew = ($this->item->ID == 0);
JToolBarHelper::title($isNew ? JText::_('COM_MK_MANAGER_MK_NEW')
: JText::_('COM_MK_MANAGER_MK_EDIT'));
JToolBarHelper::save('IA.save');
JToolBarHelper::cancel('IA.cancel', $isNew ? 'JTOOLBAR_CANCEL'
: 'JTOOLBAR_CLOSE');
}
}