I created a contact form on my classified ads website.
I use the following function to get the uploader email :
public function uploadermail()
{
return $this->User_id?$this->User->email:lang('anonymous');
}
It works fine and I get the result using an echo :
<?php echo $image->uploadermail(); ?>
Then I use a function to send the mail :
public static function sendmail_anon()
{
$form = new Form('sendmail_anon');
$form->field('email', 'text', array
(
'valid_email' => true
));
$form->field('message', 'textarea', array
(
'min_length' => 25
));
if($data = $form->validate())
{
$envoi = array
(
'message' => $data['message'],
'email' => $data['email']
);
mail($data['email'], lang('account_details'), lang('email_contact', $envoi), 'From: noreply#'.$_SERVER['HTTP_HOST']);
}
return $form;
}
The problem is that this is sending the mail to the e-mail from the form field.
I would like to replace $data['email'] and insert the uploadermail instead. I tried :
mail($image->uploadermail(), lang('account_det.....
And it returns the following error :
Fatal error: Call to a member function uploadermail() on a non-object
Is it possible to do and how should I writte it exactly ?
I tried :
mail($uploadermail,....
And it doesn't returns errors, but didn't received any mail, how can I check what exactly contains $uploadermail on the browser ?
This means that $image is not an class instance. So you cannot do $image->uploadermail().
You can check it out by doing: var_dump($image);
After posting your full code I see you are accessing that function from public static function sendmail_member():
mail($image?$image->uploadermail():$data['email'], lang('account_details'), lang('email_contact', $envoi), 'From: noreply#'.$_SERVER['HTTP_HOST']);
However $image is never declared (/ instantiated) in that scope. Upon further investigation I see that there is a method called uploadermail in the correct class which I guess you are trying to access.
So to access that method you should do:
self::uploadermail()
or
$this->uploadermail()
PS
You should really try to prevent using statics. Static stuff are basically globals and they tightly couple you code and it prevent the L in SOLID programming.
You should instantinate an object for $image before usage! e.g.
$image = new ...
or
$image = x.GetImage(...
Related
Im trying to send a email with a list of companies that have the pending or waiting status.
This list is already collected in the following function:
public static function getCompaniesAwaitingCheck()
{
$awaitingChangeApproval = self::getAwaitingChangeApproval();
$awaitingPublication = self::getAwatingPublication();
return array_merge($awaitingChangeApproval, $awaitingPublication);
}
Now I want to use that function to put in the email. I have made a separate class for this (AdminPendingApprovalNotification.php)
In there is the following function:
public function notifyPendingApproval()
{
$dailyClaimMailTitle = get_field("daily_claim_overview_mail_title", 'options');
$dailyClaimMailText = get_field('daily_claim_overview_mail_text', 'options');
$dailyClaimMailAddress = get_field('daily_claim_overview_mail', 'options');
$company = new Company();
$pendingCompany = $company->getCompaniesAwaitingCheck();
wp_mail(
$dailyClaimMailAddress,
ecs_get_template_part('views/email/template', [
'title' => $dailyClaimMailTitle,
'text' => $dailyClaimMailText, $pendingCompany,
], false),
['Content-Type: text/html; charset=UTF-8']
);
}
When I dd($pendingCompany); I get the error:PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Models\Model::__construct(), 0 passed in Emails/AdminPendingApprovalNotification.php on line 16 and exactly 1 expected
line 16: $company = new Company();
Unfortunately can’t get it to work, I’m a beginner, some help would be appreciated. Thanks!
Your method getCompaniesAwaitingCheck is static, so you should call it like:
$pendingCompany = Company::getCompaniesAwaitingCheck();
An error occured because your Company class requires arguments in the __construct method, which you didn't provide.
I'm new to PHPUnit and wondering is it possible to write a test for which ignore specific method.
The code is like examine whether $data is Valid or not, and if it find irregular data, send message to slack with it.
My question is, is it possible to run a test without sending alert message, like ignore sendAlert function?
If possible, I want to know how to write it, If not, I want know why and how to make this code testable.
Thanks!!
example code )
public static function isValid($data) {
// some code here
if (Valid) {
return true;
} else {
// some code here to find irregular
if (irregular) {
self::sendAlert($data);
}
return false;
}
}
private static function sendAlert($data) {
// send alert to slack
Example_Model_Slack::post($slackMsg, $channel);
}
<?
class Example_Model_Slack
{
public static function post($text, $channel = '') {
// make $params from $text and $channel
// POST
$stream = [
'http' => [
'method' => 'POST',
'protocol_version' => 1.1,
'content' => http_build_query($params),
],
];
return file_get_contents(self::POST_URL, false, stream_context_create($stream));
}
}
Edit after the question edit
If your code is in a namespace (which should be, it's good practice), it's extremely easy:
Create a new function in a separate file that is only included by your UnitTest file. This file should have the same namespace as your code. In this example, Example_Model_Slack is in the namespace Foobar\Models.
<?php
namespace Foobar\Models;
function file_get_contents(string $filename, bool $use_include_path = false, resource $context = ?)
{
return 'Whatever you want';
}
When you call a function, the code looks for it:
In the specifically used functions.
In the same namespace.
In the built-in functions.
Therefore, your code will use the built-in file_get_contents (namely \file_get_contents), but your test will use the one in the same namespace (namely \Foobar\Models\file_get_contents).
Original answer
The easiest would be to actually call sendAlert, but to mock the call to its content. As you didn't provide the code of that method, I can't be more precise, juste browse through the doc and figure it out by yourself or, alternatively, show us the code.
For a theorectical and general answer: your sendAlert method probably uses one that is provided by an external vendor, let's say \SlackApi\Slack::send($message). In that case, you could mock the provided \SlackApi\Slack class to replace the send method with one that doesn't actually send anything but still returns the expected data.
In my Symfony service I wanted to add small edit so I decided it's better to do it inside the class.
In my controller I am getting storyId (it's not table ID, it's a string with different chars) from my Request like:
$story = json_decode($request->getContent(), true);
$storyId = $story['storyId'];
$freeStoryName = $this->storyRepo->findOneOrFail(['storyId' => $storyId]);
$story->freeStoryName($freeStoryName);
return $this->json(["message" => "SUCCESS"]);
And In my Entity class I handle it like:
public function freeStoryName(Story $story): Story
{
$this->setPreviousStoryName($story->getStoryName());
$story->setStoryName(null);
}
And I get the error message:
Call to a member function freeStoryName() on array
I know what the message means but do not get it? It's findOne() method..
And other question will be, do I need flush() method in the Entity class like I had in a service?
You are using freeStoryName on $story which is an array (json_decode($request->getContent(), true);)
You need to use your method with your result :
$story = json_decode($request->getContent(), true);
$storyId = $story['storyId'];
$freeStoryName = $this->storyRepo->findOneOrFail(['storyId' => $storyId]);
$freeStoryName->freeStoryName($freeStoryName);
return $this->json(["message" => "SUCCESS"]);
If you feel that it's a little weird to do it this way, you could change your method to:
public function freeStoryName()
{
$this->setPreviousStoryName($this->getStoryName());
$this->setStoryName(null);
}
And use it:
$freeStoryName->freeStoryName();
I am trying to setup an array that pulls the filename and function name to run, but it not fully working.
The code is
$actionArray = array(
'register' => array('Register.php', 'Register'),
);
if (!isset($_REQUEST['action']) || !isset($actionArray[$_REQUEST['action']])) {
echo '<br><br>index<br><br>';
echo 'test';
exit;
}
require_once($actionArray[$_REQUEST['action']][0]);
return $actionArray[$_REQUEST['action']][1];
Register.php has
function Register()
{
echo 'register';
}
echo '<br>sdfdfsd<br>';
But it does not echo register and just sdfdfsd.
If I change the first lot of code from
return $actionArray[$_REQUEST['action']][1];
to
return Register();
It works, any ideas?
Thanks
Change the last line to:
return call_user_func($actionArray[$_REQUEST['action']][1]);
This uses the call_user_func function for more readable code and better portability. The following also should work (Only tested on PHP 5.4+)
return $actionArray[$_REQUEST['action']][1]();
It's almost the same as your code, but I'm actually invoking the function instead of returning the value of the array. Without the function invocation syntax () you're just asking PHP get to get the value of the variable (in this case, an array) and return it.
You'll find something usefull here:
How to call PHP function from string stored in a Variable
Call a function name stored in a string is what you want...
I am trying to develop a chat bot.
I have a doubt regarding the functionality.
Here's a part of the code:
<?php
require_once 'bootstrap.php';
require_once CB_HOME.'/library/CommonFunctions.php';
class testBot extends AbstractCbRest{
public function subscriptionCreated($userName){
return "Welcome ";
}
public function subscriptionDeleted($userName){
return "Thanks ";
}
public function messageReceived($from, $message){
return "" ; // how to return multiple here
}
In the messageReceived function ,I am going to implement the chatbot functionality.
Whenever i get a message from the user i am going to return something.For that i will have to run some php scripts and make some api calls.The final result i will send to the user.
All this is going to take approximately 20-25 seconds.
Is there a way I can send multiple return statements?
Like while the Api calls are being made i can send a message to the user and then wait for the actual result to come and then send it?
I cannot think of a way because as soon i sent a message,i cannot return something until and unless user replies with something.
Use an array :
public function messageReceived($from, $message){
return array(
'Welcome',
'Thanks',
'Hello',
'Whatever'
);
}
Or even an associative array
array(
'msg1' => 'Welcome',
'msg2' => 'Thanks',
'msg3' => 'Hello',
'msg4' => 'Whathever'
)
Then you can use a particular message with :
array['msg1']
You could create an array and return that :
public function messageReceived($from, $message){
$retval = array();
$retval[] = "message1";
$retval[] = "message2";
return $retval;
}
or
public function messageReceived($from, $message){
return array("message1","message2");
}
It sounds like you need to think about using AJAX rather than making synchronous calls while the page rendering is being processed.