I tried existing questions in the forum and I was not able to figure out how I can convert this below code using create_function. When I run the application I get a deprecated error in the logs. Can you please post the converted code?
private function _set_error_handler() {
set_error_handler(
create_function(
'$severity, $message, $file, $line',
'throw new Exception($message . " in file " . $file . " on line " . $line);'
)
);
}
set_error_handler() requires a Callable.
You can use anonymous function :
private function _set_error_handler() {
set_error_handler(
function($severity, $message, $file, $line) {
throw new Exception($message . " in file " . $file . " on line " . $line);
}
);
}
See live demo
Or a separated function :
private function _set_error_handler() {
set_error_handler([$this, 'on_error']);
}
// should be public
public function on_error($severity, $message, $file, $line) {
throw new Exception($message . " in file " . $file . " on line " . $line);
}
See live demo
Related
I'm running the following script inside a Laravel job (OperatorSubmissionJob) to upload multiple files to the SFTP server. Everything working well. But I have to disconnect the SFTP connection to end the session after the uploading finished.
$count=1;
$sftp = Storage::disk('sftp');
foreach ($request['image'] as $key => $image) {
$image_array_1 = explode(";", $image);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = Carbon::now()->format('Ymd_his') . $key . '.jpeg';
// FTP server upload
$ftp_image_name = $ftp_path . "_" . $count . '.jpeg';
try {
$isUploaded = $sftp->put("$ftp_path/" . $ftp_image_name, $data, 'public');
if ($isUploaded) {
Log::info("FTP image uploaded (UserID-" . $id . ", CustomerID-" . $mail_history->CustomerID . "): " . $count);
} else {
Log::info("FTP image upload failed (UserID-" . $id . ", CustomerID-" . $mail_history->CustomerID . "): " . $count);
}
$count++;
} catch (\Exception $e) {
Log::error($e->getMessage());
}
}
// have to disconnect $sftp here. I have tried the following:
// $sftp->disconnect(); // error: undefined method disconnect
// $sftp->getDriver()->getAdapter()->disconnect(); // error: undefined method disconnect
// $sftp->getFilesystem()->getAdapter()->getClient()->disconnect();
//
Used techs:
Laravel 9 league/flysystem-sftp-v3
None of the disconnect scripts working in my case. Please help..
I have tried with the following scripts:
$sftp->disconnect();
$sftp->getDriver()->getAdapter()->disconnect();
$sftp->getFilesystem()->getAdapter()->getClient()->disconnect();
Using Laravel framework with phpunit for unit tests.
I am working with a function that requires directories to be created for a file to be written to it, in short, the function gets data, write it to a temp file and moves the temp file once done.
public function getDataAndStoreToCSVFile() {
Log::info(date('Y-m-d H:i:s') . " -> " . __FILE__ . "::" . __FUNCTION__);
try {
// make sure directories exist
if (!Storage::has($this->temporary_directory) || !Storage::has($this->storage_directory)) {
$this->createDirectories();
}
// get full path of storage disk for files
$diskPath = Storage::getAdapter()->getPathPrefix();
// create a complete path to temporary file to allow tempnam to find the directory
$full_temporary_file_path = $diskPath.$this->temporary_directory;
// fetch stations, station networks and station params seperated by double new line,
// will return FALSE if something is missing and file will not be created and not written to
if($stations_data_array = $this->getCompleteStationsDataArray("\n\n")){
// create temporary file
$temporary_file = tempnam($full_temporary_file_path,'') ;
// if both $temporary_file and $stations_data_array exist write entries to file one at a time in CSV format
if (file_exists($temporary_file)) {
$fp = fopen($temporary_file, 'a');
foreach ($stations_data_array as $fields) {
if (is_object($fields) || is_array($fields)) {
// $fields is an array
$fields = (array)$fields;
fputcsv($fp, $fields);
} else {
// $fields is the separator
fwrite($fp, $fields);
}
}
// done writing, close file
fclose($fp);
// create new permanent name for $temporary_file in the storage directory "full_disk_path.storage_path.yyyymmddhhmmss.timestamp"
$storage_file = $diskPath . $this->storage_directory . "/" . date('YmdHis') . "." . time();
// rename $temporary_file to $storage_file
if (!rename($temporary_file, $storage_file)) {
Log::error(__FILE__ . "::" . __FUNCTION__ . " : Failed to move temporary file from " . $this->temporary_directory . " to " . $this->storage_directory);
}
} else{
Log::error(__FILE__ . "::" . __FUNCTION__ . " : Temporary file was not available or does not exist.");
}
} else {
Log::error(__FILE__ . "::" . __FUNCTION__ . " : Temporary file was not created.");
}
} catch (\ErrorException $e) {
// Catches missing directory or file, or tempnam couldn't find temporary storage path //Todo add test for this exception
Log::error(__FILE__ . "::" . __FUNCTION__ . " : " . $e->getMessage());
} catch (\Exception $e) {
// Catches uncaught exceptions
Log::error(__FILE__ . "::" . __FUNCTION__ . " : " . $e->getMessage());
}
}
To test if ErrorException is thrown when directories are missing, this test :
public function test_getDataAndStoreToCSVFile_handles_ErrorException() {
// set up data
$this->setup_all_data_for_getDataAndStoreToCsvFile_funtion();
// mock class
$mock = $this->getMockBuilder('App\Interfaces\Sources\IdbStationSourceInterface')
// stub function createDirectories, will now return null and not create directories, missing directories will throw ErrorException
->setMethods(['createDirectories'])
->getMock();
// expect the ErrorException to be thrown
$this->expectException('ErrorException');
// run function
$mock->getDataAndStoreToCSVFile();
}
When I run the test, my logs indicate that I fell into :
} catch (\ErrorException $e) {
// Catches missing directory or file, or tempnam couldn't find temporary storage path //Todo add test for this exception
Log::error(__FILE__ . "::" . __FUNCTION__ . " : " . $e->getMessage());
}
But my terminal says :
1) Tests\Interfaces\Sources\IdbStationSourceInterfaceTest::test_getDataAndStoreToCSVFile_handles_ErrorException
Failed asserting that exception of type "ErrorException" is thrown.
I have no clue where to go from there, I read and tried a couple of things but clearly I'm doing something wrong.
Edit 1 :
Tried : $this->setExpectedException("ErrorException");
But I get the following :
1) Tests\Interfaces\Sources\IdbStationSourceInterfaceTest::test_getDataAndStoreToCSVFile_handles_ErrorException
Error: Call to undefined method Tests\Interfaces\Sources\IdbStationSourceInterfaceTest::setExpectedException()
Thats because you catched the exception. PHPUnits expectedException-method only registers unhandled or rethrown exceptions. Either rethrow the exception in your catch-block or just test for the log-entry you are creating in the catch-block.
from function getDataAndStoreToCSVFile() you just throw error with error code and message. Then you can use these assertion in test case.
/**
*#expectedException ExampleException
*#expectedExceptionCode ExampleException::EceptionCode
*/
public function test_getDataAndStoreToCSVFile_handles_ErrorException() {}
I'm having a custom Static Error Logging method, as specified in the following link http://www.bbminfo.com/Tutor/php_error_error_log.php I executed the code as mentioned in the tutorial, I'm getting the output as expected. But now I moved the error handing method to a class and I made it as Static. I facing an issue its not working
class ErrorHandling {
/* Error Handling Function */
public static function bbmNotice($errNo, $errStr, $errFile, $errLine) {
$error_msg = "Custom PHP Notice : " . $errNo . "\n";
$error_msg .= "Message : " . $errStr . "\n";
$error_msg .= "Location : " . $errFile . "\n";
$error_msg .= "Line Number : " . $errLine . "\n";
/* Error Logging in General error_log File*/
error_log($error_msg, 0);
}
/* Error Handler Fixing */
set_error_handler("bbmNotice", E_USER_NOTICE);
}
/* Undefined Variable: $str */
if(isset($str)) {
echo $str ;
} else {
trigger_error("Variable 'str' is not defined, Kindly define the variable 'str' before usage.", E_USER_NOTICE);
}
I'm getting the following error
Parse error: syntax error, unexpected 'set_error_handler' (T_STRING), expecting function (T_FUNCTION) in /home2/bbminfon/public_html/error.php on line 17
Kindly assist me how to log the error in this setup.
The parse error occurs because you are trying register a function as error handler, but actually want to register a class method.
Register the error handler like this instead:
class ErrorHandling
{
/* Error Handling Function */
public static function bbmNotice($errNo, $errStr, $errFile, $errLine)
{
$error_msg = "Custom PHP Notice : " . $errNo . "\n";
$error_msg .= "Message : " . $errStr . "\n";
$error_msg .= "Location : " . $errFile . "\n";
$error_msg .= "Line Number : " . $errLine . "\n";
/* Error Logging in General error_log File*/
error_log($error_msg, 0);
}
}
set_error_handler("ErrorHandling::bbmNotice", E_USER_NOTICE);
For reference, see:
http://php.net/manual/en/language.oop5.basic.php
http://php.net/manual/en/language.types.callable.php
I am trying to run some job in background and write the result to file result from complete callback, but it does only work for addTask (not in background) and not for addTaskBackground.
Does someone have an idea?
$client = new GearmanClient();
$client->addServer('localhost');
$client->setCompleteCallback("complete");
$client->addTaskBackground('upload', 'http://youtube.com/watch?v=o3mP3mJDL2k', null, 1);
$client->addTaskBackground('upload', 'http://www.youtube.com/watch?v=SgAVnlnf8w0', null, 2);
/* in these case complete callback works
$client->addTask('upload', 'http://youtube.com/watch?v=o3mP3mJDL2k');
$client->addTask('upload', 'http://www.youtube.com/watch?v=SgAVnlnf8w0');
*/
$client->runTasks();
function complete($task){
file_put_contents('/home/vonica/public_html/test/tmp/1.txt', $task->unique() . ", " . $task->data() . "\n", FILE_APPEND);
}
$worker = new GearmanWorker();
$worker->addServer('localhost');
$worker->addFunction('upload', 'uploader');
while($worker->work()){
if ($worker->returnCode() != GEARMAN_SUCCESS) {
echo "ret code: " . $worker->returnCode() . "\n";
break;
}
};
function uploader($job){
$content = $job->workload();
exec ('echo $( youtube-dl -f worst "'.$content.'")');
return $content;
}
CompleteCallback will not be called on background task completion. If you want to check the status of background job use GearmanClient::jobStatus.
Client.php
// save this $job_handle somewhere
$job_handle = $client->doBackground('upload', 'http://youtube.com/watch?v=o3mP3mJDL2k', null, 1);
Status.php
// use previously saved job handle to check job's status
$job_handle = $_GET['job_handle'];
$stat = $client->jobStatus($job_handle);
echo "Running: " .
($stat[1] ? "true" : "false") .
", numerator: " .
$stat[2] .
", denomintor: " .
$stat[3] . "\n";
Read more here
I build a function that if you give it an array of paths it will look for a file in each path and if you give it an array of one path it will look in that path only for the file.
My questions, is when you give it an array of paths such as:
$array = array(
'template_view_paths' => array(
'path_name' => some/path/
'path_name_two' => some/path/two/
)
)
It seems to find the file in some/path/ but keeps going on to some/path/two/ and freaks out because the file doesn't exist. What would I have to change so that if it find the file in any path that it stops looking in other paths?
The code - NOT re-factored
public function render_view($template_name){
if(!isset($this->_options['template_view_path'])){
throw new AisisCore_Template_TemplateException('Not view path was set.');
}
if(is_array($this->_options['template_view_path'])){
foreach($this->_options['template_view_path'] as $template=>$path){
require_once($path . $template_name . '.phtml');
}
}else{
if(!file_exists($this->_options['template_view_path'] . $template_name . '.phtml')){
throw new AisisCore_Template_TemplateException('Could not find: ' . $template_name . '.phtml at ' . $path);
}
require_once ($this->_options['template_view_path'] . $template_name . '.phtml');
}
}
Note: the part to focus on is the if(is_array()){} loop.
Shouldn't:
if(is_array($this->_options['template_view_path'])){
foreach($templates as $template=>$path){
require_once($path . $template_name . '.phtml');
}
}else{
be:
if(is_array($this->_options['template_view_path'])){
foreach($this->_options['template_view_path'] as $template=>$path){
if (file_exists($filename = $path . $template_name . '.phtml')) {
require_once($filename);
return;
}
}
throw new AisisCore_Template_TemplateException('Could not find: ' . $template_name . '.phtml in any paths');
}else{
You're never actually looping $this->_options['template_view_path'].