The purpose of this code is just separate the config data. If i use the $config array directly in the example.php all works properly. However in the code below i get different values.
facebook.php
<?php
class Facebook extends AppController{
public function __construct() {
$config = array();
$config['appId'] = '400xxx6'; //YOUR_APP_ID
$config['secret'] = 'f70f01e76xxx7e'; //YOUR_APP_SECRET
$config['cookie'] = false;
return $config;
}
}
?>
example.php
<?php
App::import('Config', 'Facebook');
$a = new Facebook();
var_dump($a);
?>
Why $var_dump($a); return something like this?
object(Facebook)[50]
protected 'appId' => null
protected 'apiSecret' => null
protected 'user' => null
protected 'signedRequest' => null
protected 'state' => string 'e4ac55f1xxx87a88' (length=32)
protected 'accessToken' => null
protected 'fileUploadSupport' => boolean false
What I want is the original array. What is the mistake?
array
'appId' => string '400xxx6' (length=15)
'secret' => string 'f70f01e76xxx7e' (length=32)
'cookie' => boolean false
I'm pretty sure that when you do:
$a = new Facebook();
the class being instantiated is not the one you created. I believe you use Facebook PHP SDK, and their class name is also Facebook. You have conflicting class names.
Change your class name for something else like FacebookConfig and you'll be fine.
Also, it would make more sense to store your array in the class instance, something like:
class FacebookConfig extends AppController{
public $config = array();
public function __construct() {
$this->config = array();
$this->config['appId'] = '400xxx6'; //YOUR_APP_ID
$this->config['secret'] = 'f70f01e76xxx7e'; //YOUR_APP_SECRET
$this->config['cookie'] = false;
}
}
Related
i have private class with array :
class Whois{
private $whoisServers = array(
"ac"=> "whois.nic.ac",
"ae" => "whois.nic.ae",
"tech" => "whois.nic.tech",
"yu" => "whois.ripe.net");
}
now, possible i get array() for private $whoisServers from database?
Now make an object of a class and access to public function.
<?php
class Whois{
private $whoisServers = array(
"ac"=> "whois.nic.ac",
"ae" => "whois.nic.ae",
"tech" => "whois.nic.tech",
"yu" => "whois.ripe.net");
/*
!----------------------------------------------
! Getting Private Server List Using Public Function
! #getter
!----------------------------------------------
*/
public function getWhichServers()
{
return $this->whoisServers;
}
/*
https://github.com/arif98741
*/
}
$object = new Whois();
$serverlist = $object->getWhichServers();
I'm trying to pass an array i created in my testcase into my function i want to test. Is it possible to create a vairable in the testcase and pass or mock it to the class/function i want to test?
is it possible to use something like this:
$this->object = array(//array code here);
$this->testclass->attachVar->getAllObjects($this->objects);
Here is my code:
class myClassTest extends \PHPUnit_Framework_TestCase {
protected function setUp(){
$this->testclass = new \stdClass();
$this->testclass = $this->getMockBuilder('library\ixPlanta\plantChange', $this->object)
->disableOriginalConstructor()
->getMock();
}
public function testGetAllObjects() {
$this->object = array(
'testdb' => array(
'testdb_michel' => array(
'dbname' => 'testdb',
'projectName' => 'testdb',
'projectID' => 'bd993d2b9478582f6d3b73cda00bd2a',
'mainProject' => 'test',
'search' => false,
'webgroup' => array(),
'locked' => false
)
)
);
$this->testclass->expects($this->once())
->method('GetAllObjects')
->with('testdb', false, "CHECKED")
->injectTo('object', $this->object)
->will();
$result = $this->testclass->getAllObjects('testdb', false, "CHECKED");
$this->assertTrue($result);
}
In the function testGetAllObjects() i created an array that i want to pass to the function i want to test
public function getAllObjects($company,$selected=false,$selectText='CHECKED'){
$objList = array();
$i = 0;
foreach($this->Objects[$company] as $key => $value){
$objList[$i] = array('value'=> $key,'name' => $value['projectName'], 'objectID' => $value['projectID']);
$objList[$i]['checked'] = '';
if($selected !== false && !is_array($selected) && $selected === $value['dbname']){
$objList[$i]['checked'] = $selectText;
}elseif($selected !== false && is_array($selected) && in_array($value['dbname'], $selected)){
$objList[$i]['checked'] = $selectText;
}
++$i;
}
return $objList;
}
The variable i want to pass to getAllObjects is $this->objects
I think you misunderstood mock objects. The purpose of mock objects is, to create a dummy object for any other class you don't want to test. Mocking a method means, to prevent another class from calling its actual logic. Instead, it is not executed and the mock just returns whatever you gave it.
To test your actual class you just instantiate it and call its method:
class myClassTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$this->testclass = new MyClass();
}
public function testGetAllObjects()
{
$this->testclass->object = array(
'testdb' => array(
'testdb_michel' => array(
'dbname' => 'testdb',
'projectName' => 'testdb',
'projectID' => 'bd993d2b9478582f6d3b73cda00bd2a',
'mainProject' => 'test',
'search' => false,
'webgroup' => array(),
'locked' => false
)
)
);
$result = $this->testclass->getAllObjects('testdb', false, "CHECKED");
$this->assertTrue($result);
}
}
Example of a mock:
Let's say your class contains some other object of the class Service which is injected through the constructor:
class MyClass {
protected $service;
public function __construct(Service $service) {
$this->service = $service;
}
public function myMethod($argument) {
$return = $this->service->callService($argument);
return $return;
}
}
And your Service object is something like this:
class Service{
public function callService($argument) {
if($argument === NULL) {
throw new \Exception("argument can't be NULL");
}
return true;
}
}
Now you could test MyClass with this method:
public function testMyClassMethod() {
$serviceMock = $this->getMockBuilder("Service")->getMock();
$serviceMock->expects($this->any())
->method("callService")
->will($this->returnValue(true));
$myClass = new MyClass($serviceMock);
$this->assertTrue($myClass->myMethod(NULL));
}
myMethod will still return true, although Service would normally throw an Exception if $argument is NULL. But because we mocked the method, it is never actually called and the mock object will return whatever we provided in ->will($this->returnValue()).
public static $config = array(
'base_url' => '',
'environment' => '',
'database' => array(
'dbdriver' => '',
'dbhost' => '',
'dbname' => '',
'dbuser' => '',
'dbpass' => ''
),
I want to access the base_url key and assign it to a new static property $app but it is giving me syntax error of unexpected [
public static $app_path = self::config['base_url']; //unexpected [ error
You want to access variable so you have to add $.
self::$config['base_url']
Read some more about that here.
Unfortunately you can't assign any variable (even static) to other static property as you can see in linked manual page.
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
Read the manual:
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
Right here
And before you think this is a severe limitation, let me tell you why this is a blessed relief:
class Foo
{
public static $evil = array('bar' => 123);
public static $check = self::$evil['bar'];
}
Foo::$check;//all is well
But then, when you introduce late static binding (something we all love):
class Foo
{
public static $evil = array('bar' => 123);
public static $check = static::$evil['bar'];
}
class Bar extends Foo
{
public static $evil = 123;
}
Bar::$check;//OOOPS
TL;TR: statics are something like super-globals: you can initialize them with a constant expression, but they can't require state to be initialized, that would be inception madness
The way you've initilized your (static) properties, is not yet implemented in PHP
You can check this thread's explanation: https://stackoverflow.com/a/1633024/4098311
However, this is how i'm doing in my projects :
<?php
class YourClass {
public static $config = NULL;
public static $app_path = NULL;
public static $_INITIALIZED = FALSE;
public static init() {
if(!self::$_INITIALIZED) {
self::$config = array(
'base_url' => '',
'environment' => '',
'database' => array(
'dbdriver' => '',
'dbhost' => '',
'dbname' => '',
'dbuser' => '',
'dbpass' => ''
));
self::$app_path = self::config['base_url'];
self::$_INITIALIZED = TRUE;
}
}
// ....
// Your Stuf ...
// ....
}
YourClass::init();
class Settings {
public $constants = [
'database' => [
'APP_DB_HOST' => 'localhost'
],
];
}
class Constants extends Settings {
public $database = [
'APP_DB_HOST' => $settings->constants['database']['APP_DB_HOST'], // not working
];
}
I need to access parent class array values in child class. but this $settings->constants['database']['APP_DB_HOST'] is not working for some reason.
Here is the working solution
<?php
class Settings {
public $constants = [
'database' => [
'APP_DB_HOST' => 'localhost'
],
];
}
class Constants extends Settings {
public $database;
public function __construct(){
$database = [
'APP_DB_HOST' => $this->constants['database']['APP_DB_HOST'], // working
];
}
}
print_r(new Constants());
outputs:
Constants Object
(
[database] =>
[constants] => Array
(
[database] => Array
(
[APP_DB_HOST] => localhost
)
)
)
as per your comment,
if you want to do it in other class function, you can do that as well.
class Constants extends Settings {
public $database;
public function useParentHost(){
$this->database = [
'APP_DB_HOST' => $this->constants['database']['APP_DB_HOST'], // working
];
return $this->database;
}
}
and then
$test = new Constants();
print_r($test->useParentHost());
you have to declare some function to use $this, without/outside the function this will cause an error.
The variable $settings does not exist, perhaps you mean $this?
$this->constants['database']['APP_DB_HOST'];
Enjoy.
after creating inside setUp() two variables, i cant figure out how should i pass them to second function and use them.
this is my last attempt:
class adRequestTest extends PHPUnit_Framework_TestCase{
protected function setUp(){
$env = \Slim\Environment::mock([
'REQUEST_METHOD' => 'PUT',
'REQUEST_URI' => '/foo/bar',
'QUERY_STRING' => 'abc=123&foo=bar',
'SERVER_NAME' => 'example.com',
'CONTENT_TYPE' => 'application/json;charset=utf8',
'CONTENT_LENGTH' => 15
]);
$request = new \Slim\Http\Request($env);
}
function testInitFromHttpRequest_correctConstruction($request, $env){
$fixture = new AdRequest();
$fixture->initFromHttpRequest($request, $env);
}
}
i tried doing that by passing them like this as well :
function testInitFromHttpRequest_correctConstruction($request = $this->request, $env = $this->env)
but didnt work as well.
i am getting this error:
Missing argument 1 for adRequestTest::testInitFromHttpRequest_correctConstruction()
but i am passing two arguments like defined in the declaration... what am i missing here?? thx
The PHPunit framework don't pass any arguments to your function until you don't define a dataprovider (is not your case/scenario).
You can try this modified test case that define as class scope the variable you define in the setup method:
class adRequestTest extends PHPUnit_Framework_TestCase{
private $env;
private $request;
protected function setUp(){
$this->env = \Slim\Environment::mock([
'REQUEST_METHOD' => 'PUT',
'REQUEST_URI' => '/foo/bar',
'QUERY_STRING' => 'abc=123&foo=bar',
'SERVER_NAME' => 'example.com',
'CONTENT_TYPE' => 'application/json;charset=utf8',
'CONTENT_LENGTH' => 15
]);
$this->request = new \Slim\Http\Request($this->env);
}
function testInitFromHttpRequest_correctConstruction(){
$fixture = new AdRequest();
$fixture->initFromHttpRequest($this->request, $this->env);
// write here your tests/assertions...
}
}
Hope this help