use symfony form validator for Bulk-Insert - validation

i receive an CSV File from the User and I want to insert it into the Database. I want to use the Form Validation:
$pf = new ProductForm();
$old_memory_usage = 0;
while($data = $csvreader->read())
{
$mem = memory_get_usage() / 1024;
echo "Memory-Usage: " . $mem . " KB; Mem-Diff: " . $mem - $old_memory_usage . "\n";
$old_memory_usage = $mem;
$p = new Product();
$p->fromArray($data);
$pf->bind($p->toArray(), array());
if($pf->isValid())
{
$p->save();
}
else
{
//display error message to the user
}
}
This works fine when isValid() returns true. The Memory Difference is 0 KB. But if there is an Error in the "form" the memory-difference is 6-7 KB. So I get an allowed_memory error when the CSV-File is very huge.
I tryed to free the form like:
unset($pf)
$pf = null;
$pf = new ProductForm();
no success. It is just worse!
ans ideas?
thx!

You can disable doctrine profiler in your databse yml:
dev:
doctrine:
class: sfDoctrineDatabase
param:
profiler: false

Related

How can I show up the errors in Laravel when response is 500?

I have a Laravel application working on different urls. example.ch and app.example.net are working will. On the same server like app.example.net i like to run app-stage.example.net.
The application return an error 500 without an error log.
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
var_dump($kernel); // returns an object. Everything ok
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
var_dump($response) //returns error 500
I checked the php version.
I checked the fpm version.
I checked the .env file
I did "sudo chmod -R 777 bootstrap/cache storage"
I restarted the server.
I tried to show the errors.
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
No success.
What can I do in addition to find the error?
use this package Dotenv
make a file like this
and then use multiple .env for example acceptnace.env . production.env , staging.env
make a file like environment.php in bootstrap directory like this
<?php
$envPath = realpath(dirname(__DIR__));
$env = get_current_user();
if ($env == 'staging') {
$envFile = ".staging.env";
} elseif ($env == "acceptance") {
$envFile = ".acceptance.env";
} elseif ($env == "development") {
$envFile = ".development.env";
} elseif ($env == "production") {
$envFile = ".production.env";
} elseif ($env == "beta") {
$envFile = ".beta.env";
} else {
$envFile = ".local.env";
}
Dotenv\Dotenv::create($envPath, $envFile)->load();
and this will load multiple env for your app

Laravel Storing Image File Retrieved From External Url in Spesific Folder

I'm getting users' profile pictures from another site. I want to create a folder for users who have a URL for the image. Because every user's profile picture must be in its own file. This is what I want to do. I'm running with custom artisan commands.
foreach ($adminUser as $user) {
$a= DB::table('users')->where('email', $user['email'])->first();
if($a) {
echo "\n ", $a->name, " this user already exists. \n";
continue;
} else {
$a = User::create($user);
echo "\n ", $user['name'], " created. \n";
if (isset($user['link']) && strlen($user['link']) > 0) {
$folder_Path = public_path().'/user_images/' . $a->id;
File::makeDirectory($folder_Path, $mode = 0777, true, true);
$contents = file_get_contents($user['link']);
$file_name = basename($user['link']);
Storage::disk('uploads')->put($file_name, $contents);
$this->info(" |--> Profile picture uploaded.");
}
}

How to test broadcast driver?

I am wondering if its possible to test ShouldBroadcast in Laravel?
My test will trigger the even that implements ShouldBroadcast, however, I've noticed that broadcasting didn't happen.
Of course, the broadcasting event is working in the app it self.
Has any one tried such test?
It's an old question, but just in case it can help someone : i did for myself an assert function that you should add to your TestCase.php.
The idea is to set the broadcast driver to "log" and then to read the 4th line from the end to see if it's a broadcast log.
In your phpunit.xml
Add the folowing line to the node:
<env name="BROADCAST_DRIVER" value="log"/>
In your TestCase.php file
Add the folowing function :
public function assertEventIsBroadcasted($eventClassName, $channel=""){
$logfileFullpath = storage_path("logs/laravel.log");
$logfile = explode("\n", file_get_contents($logfileFullpath));
if(count($logfile) > 4){
$supposedLastEventLogged = $logfile[count($logfile)-5];
$this->assertContains("Broadcasting [", $supposedLastEventLogged, "No broadcast were found.\n");
$this->assertContains("Broadcasting [".$eventClassName."]", $supposedLastEventLogged, "A broadcast was found, but not for the classname '".$eventClassName."'.\n");
if($channel != "")
$this->assertContains("Broadcasting [".$eventClassName."] on channels [".$channel."]", $supposedLastEventLogged, "The expected broadcast (".$eventClassName.") event was found, but not on the expected channel '".$channel."'.\n");
}else{
$this->fail("No informations found in the file log '".$logfileFullpath."'.");
}
}
Instead of checking what's written in log, you can to use the assertion 'expectsEvents', which you can test if a certain event is launched.
public function testMethod(){
$this->expectsEvents(YourEventClass::class)
...your code test...
}
For more info:
https://laravel-guide.readthedocs.io/en/latest/mocking/
with Adrienc solutions with dynamically getting index of last event
private function getIndexOfLoggedEvent(array $logfile)
{
for ($i = count($logfile) - 1; $i >=0 ; $i--) {
if (strpos($logfile[$i], 'Broadcasting [Illuminate\Notifications\Events\BroadcastNotificationCreated]') !== false) {
return $i;
}
}
}
which will give you index of the line of last broadcast
I took both previous answers, and put them together.
This works with laravel 5.7.
In your TestCase.php file:
public function assertEventIsBroadcasted($eventClassName, $channel = '')
{
$date = Carbon::now()->format('Y-m-d');
$logfileFullpath = storage_path("logs/laravel-{$date}.log");
$logfile = explode("\n", file_get_contents($logfileFullpath));
$indexOfLoggedEvent = $this->getIndexOfLoggedEvent($logfile);
if ($indexOfLoggedEvent) {
$supposedLastEventLogged = $logfile[$indexOfLoggedEvent];
$this->assertContains('Broadcasting [', $supposedLastEventLogged, "No broadcast were found.\n");
$this->assertContains(
'Broadcasting [' . $eventClassName . ']',
$supposedLastEventLogged,
"A broadcast was found, but not for the classname '" . $eventClassName . "'.\n"
);
if ($channel != '') {
$this->assertContains(
'Broadcasting [' . $eventClassName . '] on channels [' . $channel . ']',
$supposedLastEventLogged,
'The expected broadcast (' . $eventClassName . ") event was found, but not on the expected channel '" . $channel . "'.\n"
);
}
} else {
$this->fail("No informations found in the file log '" . $logfileFullpath . "'.");
}
}
private function getIndexOfLoggedEvent(array $logfile)
{
for ($i = count($logfile) - 1; $i >= 0; $i--) {
if (strpos($logfile[$i], 'local.INFO: Broadcasting') !== false) {
return $i;
}
}
return false;
}
A test could look like this:
/**
* #test
*/
public function notifications_are_broadcasted()
{
$notification = factory(Notification::class)->create();
broadcast(new NewNotification($notification));
$this->assertEventIsBroadcasted(
NewNotificationEvent::class,
'private-notification.' . $notification->id
);
}

TYPO3 4.7 with ext: getcontentbyajax

The json output is not generated by Ext getcontentbyajax in TYPO3 ver. 4.7. It invokes an 500 Internal server error. In the serverlog i found the error is in line 42 of /lib/class.tx_getcontentbyajax.php.
switch(t3lib_div::_GP('todo')){
I found a 4.7 issue on:
http://lists.typo3.org/pipermail/typo3-german/2012-September/087865.html
t3lib_div::GPvar() changes to t3lib_div::_GP()
When you change all GPvar's to _GP the extension works fine.
Here the changed method main() form /lib/class.tx_getcontentbyajax.php of getcontentbyajax extension:
public function main(){
switch(t3lib_div::_GP('todo')){
case 'pagebrowser':
$href = str_replace(t3lib_div::getIndpEnv('TYPO3_SITE_URL'), '', t3lib_div::_GP('href')); // IE6 has problems
$requestedPage = file_get_contents(urldecode(t3lib_div::getIndpEnv('TYPO3_SITE_URL') . $href));
/*preg_match('/<div.*?id\=[\"]{0,1}' . t3lib_div::GPvar('part') . '[\"]{0,1}.*?>[\r\n]{0,2}<!--ajaxreplace-->[\s]{0,}(.*?)[\s]{0,}<!--ajaxreplace-->[\r\n]{0,2}<\/div>/s', $requestedPage, $matches);*/
preg_match('/<!--ajaxreplace-->(.*?)<!--ajaxreplace-->/s', $requestedPage, $matchesContent);
preg_match('/<title>(.*?)<\/title>/s', $requestedPage, $matchesTitle);
if(array_key_exists(1, $matchesContent)){
if(array_key_exists(1, $matchesTitle)){
$this->data['title'] = $matchesTitle[1];
}
$this->data['content'] = $matchesContent[1];
$this->data['success'] = true;
} else {
$this->data['content'] = 'An error occured, please reload the site or click this link to load your desired page.';
$this->data['success'] = false;
}
// hook
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['getcontentbyajax']['mainHook'])){
foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['getcontentbyajax']['mainHook'] as $_classRef){
$_procObj = & t3lib_div::getUserObj($_classRef);
$this->data = $_procObj->extraGlobalMarkerProcessor($this, $this->data);
}
}
break;
}
echo json_encode($this->data);
}

NuSOAP on XAMPP with PHP5: failed to open stream

Hey guys, I have a problem (again). This time I am trying to use NuSoap w/ XAMPP 1.7.1 which includes PHP5 and MySQL ... I wrote a soap-client:
<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the client instance
$client = new soapclient('http://localhost/mysql/helloworld2.php');
// Check for an error
$err = $client->getError();
if ($err) {
// Display the error
echo '<p><b>Constructor error: ' . $err . '</b></p>';
// At this point, you know the call that follows will fail
}
// Call the SOAP method
$result = $client->call('hello', array('name' => 'Doro'));
// Check for a fault
if ($client->fault) {
echo '<p><b>Fault: ';
print_r($result);
echo '</b></p>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<p><b>Error: ' . $err . '</b></p>';
} else {
// Display the result
print_r($result);
}
}
?>
and my soap-server:
// Enable debugging *before* creating server instance
$debug = 1;
// Create the server instance
$server = new soap_server;
// Register the method to expose
$server->register('hello');
// Define the method as a PHP function
function hello($name) {
$dbhost = 'blah';
$dbuser = 'blub';
$dbpass = 'booboo';
try{
$conn = MYSQL_CONNECT($dbhost, $dbuser, $dbpass)
or die ('Error connecting to mysql');
if( !$conn ){
return 'Hello, '.$name.' ... too bad, I cannot connect to the db!';
}
else{
$dbname = 'soaperina';
MYSQL_SELECT_DB($dbname) or die('Error connecting to '.dbname);
$queryres = #mysql_db_query(
'response',
'SELECT * FROM farben');
return 'RESPONSE: <br>';
while( $arr = mysql_fetch_array( $queryres ) ){
return $arr["ID"]." - ".$arr["Farben"]." - ".$arr["Rating"]."<br>";
}
}
}
catch(Exception $e){
return 'Sorry, '.$name.', but that did not work at all!';
}
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
I know that PHP works, the Apache works, MySQL works ... it also works together, but when I try to make it work with NuSOAP it does not work. I get following:
Warning:
SoapClient::SoapClient(http://localhost/mysql/helloworld2.php)
[soapclient.soapclient]: failed to
open stream: Ein Verbindungsversuch
ist fehlgeschlagen, da die Gegenstelle
nach einer bestimmten Zeitspanne nicht
richtig reagiert hat, oder die
hergestellte Verbindung war
fehlerhaft, da der verbundene Host
nicht reagiert hat. in
C:\xampp\htdocs\mysql\helloworld2client.php
on line 6
Warning: SoapClient::SoapClient()
[soapclient.soapclient]: I/O warning :
failed to load external entity
"http://localhost/mysql/helloworld2.php"
in
C:\xampp\htdocs\mysql\helloworld2client.php
on line 6
Fatal error: Maximum execution time of
60 seconds exceeded in
C:\xampp\htdocs\mysql\helloworld2client.php
on line 41
I have no idea what that is supposed to mean. I hope ya'll can help!!! Thnx in advance :)
I used NuSOAP version 1.7.3 with PHP5. In this NuSOAP 1.7.3, soapclient class renamed by nu_soapclient.
You can try this:
$client = new nusoap_client('http://localhost/mysql/helloworld2.php');
to give an answer to my own question: nusoap has a problem with php5 ... there are some answers and some solutions on the net (not many), but they didn't work with me. I downgraded to php4 and it works fine ...

Resources