Trouble finding to get data in ratchet websocket - websocket

I use this code in on Message function to check the data
public function onMessage(ConnectionInterface $from,$msg)
{
print_r($from->WebSocket->request->getQuery());
}
but the output of this code comes as
Guzzle\Http\QueryString Object
(
[fieldSeparator:protected] => &
[valueSeparator:protected] => =
[urlEncode:protected] => RFC 3986
[aggregator:protected] =>
[data:protected] => Array
(
)
)
why data comes empty here?

Related

Laravel: ValidationException::withMessages not sending all errors

I'm trying to make some validations in Laravel. I have a resource with nested resources, so I need to validate many things at once. I have a Level, which is composed of many Questions. So In order to validate them, I first validate the Level, and then each question one by one.
I use the following method:
public function ValidateDataAgainstModel($data) {
$book = Level::ValidationBook(); // Or Answer::ValidationBook()
$validator = Validator::make($data,
$book['rules'],
$book['messages']);
if ($validator->fails()) {
return $validator->errors();
}
return null;
}
That method is used in Level and Question, so it is the same.
Then I group all errors in a single array like this:
$errors = [];
$errors['level'] = $levelError;
$errors['questions'] = $questionsErrors; //$questionErrors is an array of each question errors
Then to check that my array is correct I make a \Log::info($errors) and get the following result:
[2018-12-12 23:47:12] local.INFO: array (
'level' =>
Illuminate\Support\MessageBag::__set_state(array(
'messages' =>
array (
'name' =>
array (
0 => 'Se requiere el nombre del nivel',
),
),
'format' => ':message',
)),
'questions' =>
array (
0 =>
Illuminate\Support\MessageBag::__set_state(array(
'messages' =>
array (
'description' =>
array (
0 => 'Se requiere la descripciĆ³n de la pregunta',
),
),
'format' => ':message',
)),
1 =>
Illuminate\Support\MessageBag::__set_state(array(
'messages' =>
array (
'description' =>
array (
0 => 'Se requiere la descripciĆ³n de la pregunta',
),
),
'format' => ':message',
)),
),
)
As you can see I have two questions with errors. In order to return this to my client, when I do the following
if ( count($errors) > 0 ) {
throw ValidationException::withMessages($errors);
}
But when the data arrives at my client, the question errors are not complete. Instead of getting an index with an array of the questions errors, I only got one question error.
Does anyone know why this is happening? It seems like is grouping the errors in a single one.
Finally, I'm adding the entire method that computes the result:
public function Create($data) {
// Create array to handle all the nested resources
$errors = [];
// Validate that the data array is correct
$levelErrors = $this->ValidateDataAgainstModel($data);
if ( !is_null($levelErrors) ) {
$errors['level'] = $levelErrors;
}
$questionsErrors = [];
foreach($data['questions'] as $questionData) {
/*
* We remove the level_id because we are validating the
* question content
*/
$validationBook = Question::ValidationBook();
unset($validationBook['rules']['level_id']);
$questionErrors = QuestionService::ValidateDataAgainstModel($questionData, $validationBook);
if ( !is_null($questionErrors) ) {
$questionsErrors[$questionData['index']] = $questionErrors;
}
}
if ( count($questionsErrors) > 0 ) {
$errors['questions'] = $questionsErrors;
}
if ( count($errors) > 0 ) {
\Log::info($errors);
throw ValidationException::withMessages($errors);
}
// Create the object
$result = Level::create($data);
return $result;
}
I don't know if the problem is the withErrors method implementation that you can see here ValidationException Source Code

Get youtube channels by name

I am facing a problem for last few hours but not come to the solution. I am trying to get youtube channel by name using php-youtube-api reference link in laravel. But I am only getting single channel in output. But i want a list of channels related name like this. When i search for any channel having name "soccerit" return me
stdClass Object
(
[kind] => youtube#channel
[etag] => "kjEFmP90GvrCl8BObMQtGoRfgaQ/I7mfLJg2NMc3uuc6rLgQDgQ-_3g"
[id] => UClENohulIkpi8JV18UJIPeg
[snippet] => stdClass Object
(
[title] => soccer
[description] =>
[publishedAt] => 2005-11-07T19:54:17.000Z
[thumbnails] => stdClass Object
(
[default] => stdClass Object
(
[url] => https://yt3.ggpht.com/-NcE9VxoZBwQ/AAAAAAAAAAI/AAAAAAAAAAA/F923oDS5GIc/s88-c-k-no/photo.jpg
)
[medium] => stdClass Object
(
[url] => https://yt3.ggpht.com/-NcE9VxoZBwQ/AAAAAAAAAAI/AAAAAAAAAAA/F923oDS5GIc/s240-c-k-no/photo.jpg
)
[high] => stdClass Object
(
[url] => https://yt3.ggpht.com/-NcE9VxoZBwQ/AAAAAAAAAAI/AAAAAAAAAAA/F923oDS5GIc/s240-c-k-no/photo.jpg
)
)
)
[contentDetails] => stdClass Object
(
[relatedPlaylists] => stdClass Object
(
[uploads] => UUlENohulIkpi8JV18UJIPeg
)
[googlePlusUserId] => 107844494883714037142
)
[statistics] => stdClass Object
(
[viewCount] => 763486
[commentCount] => 134
[subscriberCount] => 1478
[hiddenSubscriberCount] =>
[videoCount] => 32
)
)
Thanks in advance.
my code is :
YoutubeController.php
class YoutubeController extends BaseController {
public function index()
{
$youtube = new Madcoda\Youtube(array('key' => ##Yuxw99Ka7szK4'));
$channel = $youtube->getChannelByName($data['q']);
print_r($channel);
}
}
Youtube.php
public function getChannelByName($username, $optionalParams = false)
{
$API_URL = $this->getApi('channels.list');
$params = array(
'forUsername' => $username,
'part' => 'id,snippet,contentDetails,statistics,invideoPromotion'
);
if($optionalParams){
$params = array_merge($params, $optionalParams);
}
$apiData = $this->api_get($API_URL, $params);
return $this->decodeSingle($apiData);
}
public function api_get($url, $params)
{
//set the youtube key
$params['key'] = $this->youtube_key;
//boilerplates for CURL
// $url = "https://gdata.youtube.com/feeds/api/channels";
$a = $url . (strpos($url, '?') === false ? '?' : '') . http_build_query($params);
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, $a);
if (strpos($url, 'https') === false) {
curl_setopt($tuCurl, CURLOPT_PORT, 80);
} else {
curl_setopt($tuCurl, CURLOPT_PORT, 443);
}
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_SSL_VERIFYPEER, 0);
$tuData = curl_exec($tuCurl);
if (curl_errno($tuCurl)) {
throw new \Exception('Curl Error : ' . curl_error($tuCurl));
}
return $tuData;
}
It seems you are using wrong method. Method getChannelByName returns channel with exact name. If you want to search channels you should use:
// Search playlists, channels and videos, Return an array of PHP objects
$channels = $youtube->search($data['q']);
or if you want co search only videos you should choose:
// Search only Videos, Return an array of PHP objects
$channels = $youtube->searchVideos($data['q']);

ZF2 sessions (using database as a save handler) and csrf form validation

I am having some issues with a form's CSRF validation and the use of sessions which are stored in the database using ZF2.
Here is the code I have added to Module.php onBootstrap() method:
// create session which is persisted in the database
$dbAdapter = $serviceManager->get('Zend\Db\Adapter\Adapter');
$sessionTableGateway = new TableGateway\TableGateway('XXX.XXX', $dbAdapter);
$sessionOptions = new DbTableGatewayOptions();
$sessionOptions->setDataColumn('SESSION_DATA')
->setIdColumn('SESSION_ID')
->setModifiedColumn('SESSION_MODIFIED')
->setLifetimeColumn('SESSION_LIFETIME')
->setNameColumn('SESSION_NAME');
$sessionGateway = new DbTableGateway($sessionTableGateway, $sessionOptions);
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions(array(
'gc_probability' => 1,
'gc_divisor' => 1,
'use_cookies' => true
));
$storage = new SessionStorage();
$sessionManager = new SessionManager($sessionConfig, $storage);
$sessionManager->setSaveHandler($sessionGateway);
$sessionManager->start(true);
Container::setDefaultManager($sessionManager);
In the form, I am creating a standard CSRF element like this:
$this->add(array(
'name' => 'csrf',
'type' => 'Zend\Form\Element\Csrf'
));
When the form is loaded, I can see the CSRF hash in the session which is stored in the database:
__ZF|a:2:{s:20:"_REQUEST_ACCESS_TIME";d:1383673583.296492099761962890625;s:29:"Zend_Validator_Csrf_salt_csrf";a:1:{s:6:"EXPIRE";i:1383673883;}}FlashMessenger|C:23:"Zend\Stdlib\ArrayObject":21:{x:i:2;a:0:{};m:a:0:{}}Zend_Validator_Csrf_salt_csrf|C:23:"Zend\Stdlib\ArrayObject":72:{x:i:2;a:1:{s:4:"hash";s:32:"1ba5170385f4c2e2839766f19c3c2dbd";};m:a:0:{}
When I submit the form, I do not get any errors, however, it seems that the form's isValid() method is failing, and it looks like the CSRF Validation routine always gets a null value for the CSRF token from my session stored in the database.
Any ideas on what is going on here?
Thanks
If you're not having problems with sessions elsewhere in your code then this may be a form issue and not a database session issue. Make sure that the CSRF input element in your form...:
SomeForm.php
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\Form\Form;
use Zend\InputFilter\Input;
use Zend\InputFilter\InputFilter;
use Zend\Validator;
class SomeForm extends Form
{
public function __construct($name = null)
{
parent::__construct('csrf-eg');
$this->setAttribute('method', 'post');
// CSRF field
$this->add
(
array
(
'type' => 'Zend\Form\Element\Csrf',
'name' => 'your_csrf',
'attributes' => array
(
'type' => 'text',
'id' => 'divIDforCsrfField',
),
'options' => array
(
'csrf_options' => array
(
'timeout' => 600
)
),
)
);
}
}
actually has a filter attached and validation for the CSRF field:
SomeFormFilter.php
namespace Some\Form;
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\InputFilter\Input;
use Zend\InputFilter\InputFilter;
use Zend\Validator;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class SomeFormFilter implements InputFilterAwareInterface
{
public $your_csrf;
protected $inputFilter;
public function exchangeArray($data){...}
public function setInputFilter(InputFilterInterface $inputFilter){...}
public function getInputFilter()
{
if (!$this->inputFilter){
$inputFilter = new InputFilter();
$factory = new InputFactory();
// CSRF field
$inputFilter->add
(
$factory->createInput
(
array
(
'name' => 'your_csrf',
'required' => true,
'validators' => array
(
array
(
'name' => 'Csrf',
'options' => array
(
'messages' => array
(
Validator\Csrf::NOT_SAME => 'Your CSRF validation msg',
),
),
),
)
)
);
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
To get your csrf validation messages into your Action:
$SomeForm = new SomeForm();
$SomeFormValues = $this->getRequest()->getPost();
$SomeForm->setData($SomeFormValues);
$SomeFormFilter = new SomeFormFilter();
$SomeForm->setInputFilter($SomeFormFilter->getInputFilter());
if ($SomeForm->isValid($SomeFormValues))
{
$validatedData = $SomeForm->getData();
}
else
{
$SomeFormMessages = $SomeForm->getMessages();
}
$viewModel = new ViewModel
(
array
(
'SomeFormMessages' => $SomeFormMessages,
)
);
return $viewModel;

codeignite trying to get property of non-object not resolved

I am attempting to access the result set from a model query in the view. I have the following:
Controller:
$courseId = $this->session->userdata('courseId');
//echo "Course: ".$courseId;
if(isset($courseId) && $courseId != '')
{
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
}
Model:
function loadBasicDetailsEdit($courseId)
{
$this->db->select('*');
$this->db->where('course_id', $courseId);
$this->db->from('course');
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
return $query->result();
} else {
return FALSE;
}
}
and in the view I tried to print_r() and got this:
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
I tried to access this using $basicCourseDetails->title or $basicCourseDetails['title']
but neither are working. Any hint as to why this is happening?
Regards,
try this:
foreach($basicCourseDetails as $basic){
echo($basic->title);
}
or something like this:
echo($basicCourseDetails[0]->title);
This is an array of objects
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
Contains one stdObject in the array, so, first objects is 0, if there were more, then second item could have index 1 and so on. To retrieve data from the first (here is only one) stdobject you may use
echo $basicCourseDetails[0]->title; // title will be printed
You can send data to the view page by this line of code which is mentioned in above question.
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
But when you will access these data in view then you need to access all data one by one by using foreachloop in the view page.
For example if you have a view page like basic_details.php inside course folder then you need to write code like this to access these data.
foreach ($basicCourseDetails as $key => $value) {
$name = $value->name;
}
The above foreachloop can be written in view page where you want to access data.

JRegistry exists() returns empty array

I was trying to save a form data to DB. In the controller save() function there is a statement
$data = $model->validate($form, $data);
But it always returns empty. I tracked down the problem to the filter() function in /libraries/joomla/form/form.php (comes with joomla package). Here is some code (shortened):
$input = new JRegistry($data);
$output = new JRegistry;
foreach ($fields as $field)
{
// Initialise variables.
$name = (string) $field['name'];
if ($input->exists($name)){
$output->set($name, $this->filterField($field, $input->get($name, (string) field['default'])));
}
}
$input looks like :
JRegistry Object ( [data:protected] => stdClass Object ( [jform] => stdClass Object ( [title] => Utility Model/Patent application [ap_name] => d ...) [option] => com_eipoapplications [task] => save ) )
And each $name in the loop always contain the form element name (like 'title', 'ap_name' ... ).
But the if conditional statement always returns false. Does any one help me know why JRegistry exists() function is not finding the elements?
I think you are having an inconsistency between form and data.
Let's say the form contains a field with name title.
$data array should have a value under key of same name:
$data = array(
'title' => 'Utility Model/Patent application',
'ap_name' => 'd'
);
Or using print_r
Array
(
[title] => Utility Model/Patent application
[ap_name] => d
)
If there's no data for such field, validation is omitted. If all data keys are wrong, function returns empty array.
The question is, how it happened :/

Resources