I used PHPUnit to test a function with contents:
$fp = fopen($file_path,'wb');
if( $fp === false ) {
...
}
$ret = fwrite($fp, $content) ;
if( $ret === false ) {
...
}
I have a problem, fopen always return a resource and fwrite always return a integer value but i want them return FALSE.
How should i do?
Thank everyone :).
You could write a FileHandler class encapsulating all the file handling parts so you can inject a stub for it in your tests and setup the stub to return what you want in the different tests. You don't have to test that library functions work, only that you are calling them as expected
Related
I'm on php#8.1.3. When I have one method both creating and reading from a tmpfile, everything works as expected:
class TmpFileReadRightAway
{
public function storeToTempFileAndReadRightAway(string $content): string
{
$fh = tmpfile();
$path = stream_get_meta_data($fh)['uri'];
fwrite($fh, $content);
return file_get_contents($path);
}
}
echo (new TmpFileReadRightAway())->storeToTempFileAndReadRightAway('this works as expected');
Yet when I split the method into multiple methods, the tempfile() is deleted after the method in which it was created returns.
This is not at all what I expected as I wanted to keep the file around. I would expect the tmpfile to be deleted at termination of the php code at the very end, not after it exits the method.
class TmpFileStoreButReadLater
{
public function storeButReadLater(string $content): string
{
$path = $this->getPath($content);
return file_get_contents($path); // file at path doesn't exist anymore here, why?
}
private function getPath($content): string
{
$fh = tmpfile();
$path = stream_get_meta_data($fh)['uri'];
fwrite($fh, $content);
return $path;
}
}
This would throw
PHP Warning: file_get_contents(/tmp/phpQsUdA5): Failed to open stream: No such file or directory
Why is the file being deleted in this case and how do I ensure it exists during the runtime of my code?
Use class property.
The tmpfile() document said.
The file is automatically removed when closed (for example, by calling
fclose(), or when there are no remaining references to the file handle
returned by tmpfile()), or when the script ends.
So, I assume that when method exits, the fclose() is called automatically.
The error about failed to open stream is not just occur in PHP 8.1 but all version since PHP 7.0 to 8.1. (I don't have PHP 5.x to test with.)
To prevent that, set the $fh to class property instead.
class TmpFileStoreButReadLater
{
protected $fh;
public function storeButReadLater(string $content): string
{
$path = $this->getPath($content);
return file_get_contents($path); // file at path doesn't exist anymore here, why?
}
private function getPath($content): string
{
$this->fh = tmpfile();
$path = stream_get_meta_data($this->fh)['uri'];
fwrite($this->fh, $content);
return $path;
}
}
echo (new TmpFileStoreButReadLater())->storeButReadLater('this works as expected');
Tested on PHP 7.0 - 8.1.3 but no errors now.
I'd like to perform an operation on the php://input stream but also return it.
For example, what I'd like to achieve is that:
php://input ==> OPERATION ==> php://input
Is that possible to make something like that ?
$input = fopen("php://input", "r");
$output = fopen("php://input", "w");
while (($buffer.= fgets($input, 1024)) !== false) {
// Do something with that buffer
// ??
fwrite($output, $buffer);
}
fclose($output);
fclose($input);
If you are fine with one of the operations supported as a filter in php, you can use the php://filter fopen wrapper.
Let's say you want to base64 decode the data for example:
$data = file_get_contents('php://filter/read=convert.base64-decode/resource=php://input');
Or:
$input = fopen('php://filter/read=convert.base64-decode/resource=php://input');
// now you can pass $input to somewhere and every read operation will
// return base64 decoded data ...
However, the set of operations supported as a filter in PHP is quite limited. If it does not fit your needs I would suggest to wrap the file pointer, in a class maybe. Here comes a very basic example, you might add buffering, caching or whatever...
class Input {
public static function read() {
return $this->process(file_get_contents('php://stdin'));
}
public function process($data) {
return do_whatever_with($data);
}
}
Then in the application code use:
$input = Input::read();
I have an interesting problem and have searched the internet, but haven't yet found an answer.
I work for a company that doesn't allow it's workers to utilize OOP, it is kind of ridiculous, but the working experience is valuable.
Consider the following function:
function get_setting_values_from_file( $parameter )
{
exec("/usr/var/binary --options $parameter", $output, $return);
$settings = file( $output[0] );
foreach( $settings as $setting ) {
if( strstr( $setting, "color") ) {
$setting = explode( ":", $setting );
return $setting[1];
}
}
return false;
}
I need to unit test a similar function. I am currently using phpUnit for my tests and the vfsStream libraries to mock the file system, but how do you mock the call to exec("/usr/var/binary --options $parameter", $output, $return) when I'm developing with no access to the actual system? What is the recommend approach for dealing with test cases like this?
All feedback is appreciated.
You could mock exec() by using a function mock library. I made one (php-mock) for you which requires you to use namespaces
namespace foo;
use phpmock\phpunit\PHPMock;
class ExecTest extends \PHPUnit_Framework_TestCase
{
use PHPMock;
public function testExec()
{
$mock = $this->getFunctionMock(__NAMESPACE__, "exec");
$mock->expects($this->once())->willReturnCallback(
function ($command, &$output, &$return_var) {
$this->assertEquals("foo", $command);
$output = "failure";
$return_var = 1;
}
);
exec("foo", $output, $return_var);
$this->assertEquals("failure", $output);
$this->assertEquals(1, $return_var);
}
}
Simply mock this function to return the text that you are trying to get into $settings. You do not need to call the executable, simply create the file or return.
For instance, assuming the function get_setting_values_from_file() returns the settings as an array, you can simply mock the function in your test to return the settings as an array. Create a test stub to mock the object that contains the get_setting_values_from_file() method, and have that mock simply return the same FALSE, 1 or 2 that the test assumed.
$stub = $this->getMock('GetSettingsClass');
$stub->expects($this->any())
->method('get_settings_from_file')
->will($this->returnValue(0));
This is from the PHPUnit manual -> http://phpunit.de/manual/3.8/en/test-doubles.html#test-doubles.stubs
Optionally, you could even bypass the call, and simply test the functions/code that works on the returns by creating the array and passing it to those functions.
Assumed Example in the main code:
...
$settings = get_setting_values_from_file( 'UserType' );
$UserType = get_user_type($settings);
return $UserType;
function get_user_type($settings)
{
if($settings !== FALSE) // Returned from your function if parameter is not found
{
switch($settings)
{
case 1:
return 'User'; // Best to use Constants, but for example here only
break;
case 2:
return 'Admin';
break;
...
}
}
else
{
return FALSE;
}
}
Now, in your test, you can simply
$this->assertFalse(get_user_type(FALSE, 'Ensure not found data is handled properly as FALSE is returned');
$this->assertEqual('User', get_user_type(1), 'Test UserType=1');
$this->assertEqual('Admin', get_user_type(1), 'Test UserType=2');
...
These work as the code does not call the function that had to mock the read from the OS, but does handle all the expected returns by calling the function processing the setting return value. Here, you have simply assumed the return from the function 'get_setting_values_from_file()' without needing the file or any mocks.
This does NOT however test reading from the file, which I would do in another test by using the setUp and tearDown to actual create a file with the values you want (fopen/fwrite) and then call your function and ensure it returns what is expected.
I hope this helps to explain what I was thinking.
I'm new to OOP terminology, I am trying to create a class that make a hit counter.
I try the code below but it create just a counter.txt page with inside value 1. I dont know why its not incrementing.
class LOGFILE {
public function READ($FileName) {
$handle = fopen($FileName, 'r');
$fread = file_get_contents($FileName);
return $fread;
fclose($handle);
}
public function WRITE($FileName, $FileData) {
$handle = fopen($FileName, 'w');
$FileData = $fread +1;
fwrite($handle, $FileData);
fclose($handle);
}
}
$logfile = new LOGFILE();
$logfile -> WRITE("counter.txt",$FileData);
echo $logfile -> READ("counter.txt");
The reason is that $fread is local variable for both READ and WRITE methods. You need to make it private global variable for your class:
class LOGFILE {
private $fread;
public function READ($FileName) {
$this->fread = file_get_contents($FileName);
return $this->fread;
}
public function WRITE($FileName) {
$this->READ($FileName);
$handle = fopen($FileName, 'w');
$FileData = $this->fread +1;
fwrite($handle, $FileData);
fclose($handle);
}
}
$logfile = new LOGFILE();
$logfile -> WRITE("counter.txt");
echo $logfile -> READ("counter.txt");
Note: I have removed fopen and fclose because file_get_contents does not need it. In write you can use file_put_contents. Removed not used variable $FileData too. It's always a good practice to create variables methods and classes when they are needed.
Also take a look at best practices how to name your classes, variables, methods and so on. Here's best guide, IMO.
Let's start going over the corrected code and see what was missing:
<?php
class LOGFILE {
public function READ($FileName) {
$handle = fopen($FileName, 'r');
$fread = fgets($handle, 8192);
fclose($handle);
return $fread;
}
public function WRITE($FileName, $FileData) {
$counter = $this->READ($FileName);
$handle = fopen($FileName, 'w');
fwrite($handle, $FileData + $counter);
fclose($handle);
}
}
$logfile = new LOGFILE();
$FileData = 1;
$logfile -> WRITE("counter.txt",$FileData);
echo $logfile -> READ("counter.txt")."\n";
$logfile -> WRITE("counter.txt",$FileData);
echo $logfile -> READ("counter.txt")."\n";
?>
use of fgets instead of file_get_contents in READ (you can choose to use file_get_contents but I rather stay consistent with the other function that uses fopen)
use of READ inside function WRITE (the principal of code-reuse)
open of file with write permissions in WRITE: 'w'
init $FileData = 1;
no need to hold a private member: $fread
most important: do not write statements after return (like you did in READ) - statements that are written after return will not be executed!
This solution was tested successfully.
OOP must be used where it's needed. You need a simple thing so, no need of OOP.
<?php
function addValue($file='counter.txt', $amount=1) {
if( false == is_file($file) ) {
return false;
}
$initial = file_get_contents($file);
return #file_put_contents($initial+$amount);
}
addValue();
?>
Test your OOP knowledge on something complex, like a shopping cart or some other concept.
EDIT // so, if you need a simple example that looks complex, here you go :)
<?php
class log {
public $file = '';
private $amount = 0;
public function __construct( $file ) {
$this->file = $file;
$this->amount = 1;
}
public function makeAdd() {
$initial = file_get_contents($this->file);
return #file_put_contents($this->file, $initial + $this->amount);
}
function __call($f, $args) {
switch( $f ) {
case 'add':
if(isset($args[0]) && !empty($args[0])) {
$this->amount = (int)$args[0];
}
if( $this->amount == 0 ) {
throw new Exception('Not a valid amount.');
}
return $this->makeAdd();
break;
}
}
}
try {
// create log
$L = new log('count.txt');
// this will add 2
var_dump($L->add(2));
// this will also add 2
var_dump($L->add());
// until you rewrite the amount
var_dump($L->add(1));
// final result -> 5
} catch(Exception $e) {
die($e->getMessage());
}
?>
Good luck!
Use UpperCamelCase for class names. LogFile, not LOGFILE. When you have a variable and the most interesting thing about it is that it's expected to hold a reference to something that is_a LogFile you should name it logFile.
Use lowerCamelCase for functions. read and write, not READ and WRITE
No spaces around the arrow operator
Code after a return statement in a method can never be reached, so delete it.
read() does not use the handle returned by fopen, so don't call fopen
the temp variable $freed doesn't help us understand the code, so we can lose it
read is a slightly unconventional name. If we rename the function to getCount it will be more obvious what it does.
You said you wanted to make a hit counter. So rename the class from LogFile to HitCounter, and the variable to hitCounter
the $FileData parameter to write doesn't get used because the variable is re-assigned inside the function. We can lose it.
The write method is supposed to add one to the number in the file. Write doesn't really express that. Rename it to increment.
Use a blank line between functions. The procedural code at the end should generally be in a separate file, but here we can just add a couple of extra lines. Delete the blanks between the last three lines of code.
Don't repeat yourself - we shouldn't have to mention 'counter.txt' more than once. OOP is all about combining data structures and behaviour into classes, so make a class private variable to hold the filename, and pass it via a constructor
$fread doesn't exist in the scope of increment, so we can't use it. This won't work. Replace it with a call to to getCount()
Swap the first two lines of increment, so we're not doing two concurent accesses to the same file, although we might be running inside a server that's running our script twice and still doing two concurrent accesses.
Rename the variable $FileData to $count, since that's what it is.
Replace the fopen,fwrite,fclose sequence with file_put_contents, since that does the same thing and is more succinct.
We need tag, since our php code continues to the end of the file.
That leaves us with:
<?php
class HitCounter {
private $fileName;
public function __construct($fileName){
$this->fileName = $fileName;
}
public function getCount() {
return file_get_contents($this->fileName);
}
public function increment() {
$count = $this->getCount() + 1;
file_put_contents($this->fileName, $count);
}
}
$hitCounter = new HitCounter("counter.txt");
$hitCounter->increment();
echo $hitCounter->getCount();
You can create a static counter and increment it each time (instead of create file)
<?php
class CountClass {
public static $counter = 0;
function __construct() {
self::$counter++;
}
}
new CountClass();
new CountClass();
echo CountClass::$counter;
?>
I create a plugin for WordPress that requires two files to be exists in order to operate normaly.
The first file is defined as a file system path and the second file is defined as a URL.
Let's say the first file is that:
/home/my_site/public_html/some_folder/required_file.php
and the second file is that:
http://www.my_site.com/some_folder/required_url_file.php
Note that both files are not the same file into the file system. The required_file.php has other content than the required_url_file.php and they act absolutly diferent
Any idea on how to validate the existance of both files ?
You can check both:
$file = '/home/my_site/public_html/some_folder/required_file.php';
$url = 'http://www.my_site.com/some_folder/required_url_file.php';
$fileExists = is_file($file);
$urlExists = is_200($url);
$bothExists = $fileExists && $urlExists;
function is_200($url)
{
$options['http'] = array(
'method' => "HEAD",
'ignore_errors' => 1,
'max_redirects' => 0
);
$body = file_get_contents($url, NULL, stream_context_create($options));
sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);
return $code === 200;
}
Based on Maor H. code sample, here is a function I am using in my plugins:
/**
* Check if an item exists out there in the "ether".
*
* #param string $url - preferably a fully qualified URL
* #return boolean - true if it is out there somewhere
*/
function webItemExists($url) {
if (($url == '') || ($url == null)) { return false; }
$response = wp_remote_head( $url, array( 'timeout' => 5 ) );
$accepted_status_codes = array( 200, 301, 302 );
if ( ! is_wp_error( $response ) && in_array( wp_remote_retrieve_response_code( $response ), $accepted_status_codes ) ) {
return true;
}
return false;
}
I've made this a method in a helper class, however putting this in your theme's functions.php file should make it generally accessible everywhere. However you should always be writing in classes and instantiating them. It is much better for isolating your plugin and theme functionality.
With this in place you can simply use:
if (webItemExists('http://myurl.com/thing.png')) {
print 'it iexists';
}
Most often you will be using WordPress calls to access all items via a relative or fully qualified URL. If you have a relative reference to something such as /uploads/2012/12/myimage.png you can convert those to a fully qualified URL v. a WordPress relative URL by simply adding get_site_url(). $string when calling the webItemExists() function.
As for validating the URL, none of these answers are considering the correct, WordPress way to carry out this task.
For this task wp_remote_head() should be used.
Here's an article I've written about How To Check Whether an External URL Exists with WordPress’ HTTP API. Check it out and figure out how it works.
$file_exists = file_exists($path);
$url_accessable = http_get($url, array("timeout"=>10), $info); // should not be FALSE
$status_code = $info['response_code'] //should be 200
This seems to work for me:
function url_file_exists($url) {
$context = stream_context_create(array('http' =>array('method'=>'HEAD')));
$fd = #fopen($url, 'rb', false, $context);
if ($fd!==false) {
fclose($fd);
return true;
}
return false;
}
If you have PECL http_head function available, you could check if it returns status code 200 for the remote file.
To check if you can access the local file, could use file_exists, but this does not grant that you will be able to access that file. To check if you can read that file, use is_readable.
To check if a file exists, use the file_exists method.
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
if(! (file_exists($url1) && file_exists($url2)) ) {
die("Files don't exist - throw error here.");
}
// Continue as usual - files exist at this point.
remote:
$file = 'http://www.my_site.com/some_folder/required_url_file.php'
if ( #fclose(#fopen($file,"r")) ) echo "File exists!";
local:
$file = '/home/my_site/public_html/some_folder/required_file.php';
if ( is_file($file) ) echo "File exists!";
Use function file_exists()
file_exists('http://www.my_site.com/some_folder/required_url_file.php');
will get you results as True or false.
Checking if a file exists:
if (file_exists('path/to/file.txt')) {
echo "File exists!";
} else {
echo "File doesn't exist.";
}
Checking if a URL is valid:
$data = #file_get_contents("http://url.com/");
if (!$data) {
echo "URL not valid.";
} else {
echo "URL is valid.";
}
Notes:
Ideally you shouldn't try and predict the filesystem. Whilst methods such as file_exists are very helpful, they shouldn't be relied upon and instead you should attempt to write to files, read from them, etc, and then catch and handle any exceptions or errors that occur.