I know this question is asked like a hundred times in hundred different ways. But I just can't get this particular one to work. I am really confused.
This is the very beginning of my script:
<?php
class API {
protected static $message, $data, $status, $session, $token, $dbo, $app;
const FAIL = 0;
const SUCCESS = 1;
const INCOMPLETE_ARGS = 2;
const GROUP_ALLOW = array(5);
public static function Init() {
global $app;
self::$status = false;
self::$message = "Invalid request.";
self::$data = "";
}
public static function Render() {
echo preg_replace("/\\\\u([0-9abcdef]{4})/", "&#x$1;", json_encode(array(
"status" => self::$status,
"message" => self::$message,
"data" => self::$data))
);
}
Then there is this function:
public static function Login() {
$email = (isset($_REQUEST['email'])) ? $_REQUEST['email'] : "";
$password = (isset($_REQUEST['password'])) ? $_REQUEST['password'] : "";
require_once ("../app/Mage.php");
umask(0);
ob_start();
session_start();
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$b2bwebsiteid = Mage::getStoreConfig('base/general/b2bwebsite');
//$websiteId = Mage::app()->getWebsite()->getId();
//$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $b2bwebsiteid;
$customer->loadByEmail($email);
$countryCodeBE = $customer->getDefaultBillingAddress()->getCountry();
$countrybe = Mage::getModel('directory/country')->loadByCode($countryCodeBE);
$countryid = $countrybe->getCountryId();
.....
.....
And in between there is a lot more code and functions.
Now a bit further, there is another function:
public static function ProductInfoNew() {
And now the thing I want, is to load the variable $countryid from that first function in the ProductInfoNew function so that I can do something like this:
if ($countryid == "BE") {
$groupid = 6;
}
else {
$groupid = 4;
}
But the output always seems to be NULL or Empty.
I tried setting the $countryid variable as global, static, tried to load the variable with self:: and I tried so many things but I can't get it to work.
Does anyone know the correct solution to do this?
Thanks a lot in advance.
$countryid should be a field inside of the class you are using.
class API {
private static $country_id;
public static function ProductInfoNew() {
if (self::$country_id == "BE") {
$groupid = 6;
} else {
$groupid = 4;
}
}
}
Related
I Have this problem: I should get a variable declared in a class and use it into the same class but I don't receive error and it don't work. This is my code:
<?php
class internal {
protected $settings;
private $ctoken = '';
private $fparam = '';
private $token = '';
function __construct($ctoken, $fparam, $token){
$this->ctoken = $ctoken;
$this->fparam = $fparam;
$this->token = $token;
}
public function settings($settings = ['disable_web_page_preview' => 'false', 'parse_mode' => 'HTML', 'MySQL' => true, 'PostgreSQL' => true])
{
$this->settings = $settings;
echo 'Settings caricate!';
}
public function botAdmin($user_id = null)
{
if($user_id == NULL){
$user_id = $this->user_id;
}
if(in_array($user_id, $this->settings()['admins'])){
return true;
}else{
return false;
}
}
public function SecTest()
{
if($this->ctoken != $this->fparam or $this->token == NULL){
die("Security test: not passed, script killed.");
}else{
echo "Security test: OK. <br />";
echo json_encode($this->settings);
}
}
public function getSettings(){
return $this->settings;
}
}
I don't know what to do, I don't receive any error but if I call the method SecTest it print "null"
Before your _construct method define the variables that are specific to your class.
class internal {
private $ctoken = '';
private $fparam = '';
private $token = '';
function __construct($ctoken, $fparam, $token){
$this->ctoken = $ctoken;
$this->fparam = $fparam;
$this->token = $token;
}
Fixed, I was calling the method that echo the settings before declare the settings.
I am sending a ajax request in function and calling model function but model function not calling and i also try a local controller function but not call any local function
controller
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.controller');
class IgalleryController extends JControllerLegacy
{
function __construct($config = array())
{
$config['base_path'] = JPATH_SITE.'/components/com_igallery';
parent::__construct($config);
}
function ajaxrequest()
{
//JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_igallery/models', 'category');
//echo $db = JFactory::getDBO();
$model = $this->getModel('category');
$this->params = JComponentHelper::getParams('com_igallery');
$this->source = JRequest::getCmd('igsource', 'component');
//
$igid = JFactory::getApplication()->input->get('igid');
$Itemid = JFactory::getApplication()->input->get('Itemid');
$this->catid = JRequest::getInt('igid', 0);
$this->category = $model->getCategory($this->catid);
$profileId = JRequest::getInt('igpid', 0);
$profileId = $profileId == 0 ? $this->category->profile : $profileId;
$user = JFactory::getUser();
//print_r($user); die;
$this->profile = $model->getProfile($profileId);
$searchChildren = JRequest::getInt('igchild', 0);
$tags = JRequest::getVar('igtags', '');
//
$limit = JRequest::getInt('iglimit', 0);
$limit = $limit == 0 ? 1000 : $limit;
$foo = $this->foo();
print_r($foo);
$this->photoList = $model->getCategoryImagesList($this->profile, $this->catid, $tags, $searchChildren, $limit);
//
print_r($this->photoList);
}
function $this->foo()
{
return true;
}
...
in above code also print $foo variable but not get true or 1 value;
You must override function getModel() in your controller
parent model has construct:
public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true))
You lacked $prefix and you also add include path of the model file if necessary
Regarding issue return value true of false, you must echo 1 for true of 0 for false and stop the process by die function. The return method will show so much html of joomla page.
function $this->foo()
{
echo 1;
die;
}
I need help with PHPUnit and some methods. How should you guys write tests in PHPUnit to reach a high code coverage for the following properties and methods?
I'm pretty new to PHPUnit and could need some help. I've just write some test cases for more basic code. This class generates flash messages for the end user, and store it in a session.
Extremely grateful for some help. Any ideas?
private $sessionKey = 'statusMessage';
private $messageTypes = ['info', 'error', 'success', 'warning']; // Message types.
private $session = null;
private $all = null;
public function __construct() {
if(isset($_SESSION[$this->sessionKey])) {
$this->fetch();
}
}
public function fetch() {
$this->all = $_SESSION[$this->sessionKey];
}
public function add($type = 'debug', $message) {
$statusMessage = ['type' => $type, 'message' => $message];
if (is_null($this->all)) {
$this->all = array();
}
array_push($this->all, $statusMessage);
$_SESSION[$this->sessionKey] = $this->all;
}
public function clear() {
$_SESSION[$this->sessionKey] = null;
$this->all = null;
}
public function html() {
$html = null;
if(is_null($this->all))
return $html;
foreach ($this->all as $message) {
$type = $message['type'];
$message = $message['message'];
$html .= "<div class='message-" . $type . "'>" . $message . "</div>";
}
$this->clear();
return $html;
}
I have setup an setup-case, like this:
protected function setUp() {
$this->flash = new ClassName();
}
Also tried one test case:
public function testFetch() {
$this->assertEquals($this->flash->fetch(), "statusMessage", "Wrong session key.");
}
But gets an error message telling me: "Undefined variable: _SESSION"
If I then try:
public function testFetch() {
$_SESSION = array();
$this->assertEquals($this->flash->fetch(), "statusMessage", "Wrong session key.");
}
I get another error message telling: "Undefined index: statusMessage"
Try something like this:
function testWithoutSessionKey() {
$_SESSION = array();
$yourClass = new YourclassName();
$this->assertNull($yourClass->html()); }
function testWithSomeSessionKey() {
$_SESSION = array( 'statusMessage' => array(...));
$yourClass = new YourclassName();
$this->assertSame($expect, $yourClass->html());
}
You can't instantiate your class in the setup because your constructor need that the SESSION variable may exist(so you can test that can have some value inside).
You can evalutate (assert) only the ouptput of a method, so you can't assert that the message of the return of the method fetch.
In your method testFecth you have found a bug! Thanks to the test for this. Try fixing it with checking as you do in the construct :
public function fetch() {
if (isset($_SESSION[$this->sessionKey]))
$this->all = $_SESSION[$this->sessionKey];
}
Hope this help
I am having some problem with scope i assume, but i cannot for the life of me figure out what that problem is...
I keep getting a function undefined error for the following three functions whenever they are called; addUser, removeUser, updatePlayer. Anyone have any idea what's wrong? full code below (it is a pocketmine plugin):
<?php
/*
__PocketMine Plugin__
name=X
description=X
version=0.0.1
author=X
class=X
apiversion=10
*/
class X implements Plugin {
private $api;
public $continents = array();
public $allContinents = array("NA" => 0, "SA" => 0, "AF" => 0, "AS" => 0, "OC" => 0, "EU" => 0);
public function __construct(ServerAPI $api, $server = false){
$this->api = $api;
}
public function init(){
//Initialize the on player join event handler
$this->api->addHandler("player.spawn", array($this, "onPlayerJoin"));
$this->api->addHandler("player.quit", array($this, "onPlayerQuit"));
//Setup Config
$this->path = $this->api->plugin->configPath($this);
$this->msgs = new Config($this->path . "config.yml", CONFIG_YAML, array("AuthToken" => "", "Delay" => "5"));
$this->msgs = $this->api->plugin->readYAML($this->path . "config.yml");
}
// <--- updatePlayer --->
public function updatePlayer($user) {
}
// <--- Country Handler --->
public function addUser($user, $continents, $allContinents) {
$ip = $user->ip;
$username = $user->username;
$gi = geoip_open($this->path ."GeoIP.dat",GEOIP_STANDARD);
$continent = geoip_continent_code_by_name($gi, $ip);
array_push($continents, $username);
$continents[$username] = $continent;
$allContinents[$continent] += 1;
return $continents;
return $allContinents;
}
public function removeUser($user, $continents, $allContinents) {
$username = $user->username;
$continent = $continents[$username];
unset($continents[$username]);
$allContinents[$continent] -= 1;
return $continents;
return $allContinents;
}
// <--- Rquest Ad --->
public function requestAd() {
}
/*public function send() {
while(true) {
sleep(240);
}
}
}*/
//On player join event handler
public function onPlayerJoin($user){
$username = $user->username;
addUser($user);
updatePlayer($user);
//Check if plugin is setup
if ($this->api->ban->isOp($username) && $this->msgs["AuthToken"] == "") {
$this->api->chat->sendTo(false, "Please visit X to setup X.", $username);
}
}
public function onPlayerQuit($user){
removeUser($user);
}
public function __destruct(){
}
}
?>
If you're calling them from the same class or an extended class then you need to use $this.
public function onPlayerJoin($user){
$username = $user->username;
$this->addUser($user);
$this->updatePlayer($user);
}
Unless it's a static function, then you would use self::.
You need to instantiate an instance of class X, then call the functions as members of that object. For example:
$myX = new X();
$myX->addUser();
Cheers
EDIT I've updated the question with actual code. Turns out it was not a scope issue but a stupid mistake on my part. While testing that all value were good I was really setting them to empty.
After reading the answer below I realized I have the scope figured out but had a typo in the code.
Sorry
<?php
abstract class PHPFoo_XYZ
{
protected $_postData = array();
public function processXYZ(array $postData)
{
$this->_postData = $postData;
}
protected function _checkProcessId()
{
// doing nothing
}
}
?>
<?php
require_once dirname(__FILE__) . '/../PHPFoo/XYZ.php';
class App_XYZ extends PHPFoo_XYZ
{
protected $_UserData = array();
protected $_UserId = 'notset';
protected $_UserName = '';
public $_msg = '';
public function processXYZ(array $postData)
{
$this->_postData = $postData;
$this->_getUserData();
$this->_checkProcessId();
}
protected function _checkProcessId()
{
$this->_writeLog("User Name ".$this->_UserName);
$this->_writeLog("User Id ".$this->_UserId);
// These show empty
}
public function _getUserData() {
$UserData = array();
$UserId = array();
$User_Name = array();
$msg = '';
// Get data from database
$this->_UserId = $UserId[0]['item_id'];
// Get data from database
$this->_UserName = $User_Name[0]['title'];
// Get full data
// $results = Array of values from database
foreach ($results as $key => $value) {
$UserData[$results[$key]['fielddef_id']] = $results[$key]['value'];
}
$this->_UserData = $UserData;
$this->_writeLog("USER DATA FULL");
$this->_writeLog("User Name ".$this->_UserName);
$this->_writeLog("User Id ".$this->_UserId);
$msg = '';
foreach ($this->_UserData as $k => $v) {
$msg .= "\n".$k." == ".$v;
}
$this->_writeLog("User Data\n".$msg);
// The above output is good
if($this->_UserData = '' || $this->_UserId = '' || $his->_UserName = '') {
$this->_writeLog("There was an error getting User Data.");
return false;
}else{
return true;
}
}
}
There is something wrong from beginning, you should write "public function" when you declare a function, not "public functions", and there must be the word "function" declaring a method, not just the name.
Also you are calling a method myfunc1, when it doesn't exists and you have made another mistake when you call func2 (you wrote fucn2).
So, if you fix your code, it works as you want.
Here I fixed it for you:
<?php
abstract class foo {
protected $_var1 = '';
protected $_var2 = '';
public function func1() {
#code...
}
public function func2() {
#code..
}
}
class bar extends foo {
protected $myvar1 = '';
protected $myvar2 = '';
public function myfunc() {
// do some code to fill myvar1 to be used in other functions
$this->myvar1 = 'some data';
echo "my var " . $this->myvar1;
}
public function func2() {
// do some code that uses myvar1 data
// but $this->myvarf1 is empty here why?
echo $this->myvar1;
}
public function runit() {
$this->myfunc();
$this->func2();
}
}
//requre file
$callclass = new bar;
$callclass->runit();
?>
So please be careful before asking and if you can/want use an ide like netbeans for php to avoid this mistakes.
Have a good night.