Partial mocking a Facade ignores the variables that are set in the constructor

I have a class names AbcService

<?php

namespace AppHttp;

class AbcService
{

    private string $attr;

    public function __construct()
    {
        $this->attr = 'some text';
    }

    public function aMethod(): bool
    {
        if (empty($this->attr)) {
            return true;
        }

        return false;
    }

    public function bMethod()
    {
        return 'what';
    }

}

I’ve created a facade on top of that:

<?php

namespace AppHttp;

use IlluminateSupportFacadesFacade;

class Abc extends Facade
{
    protected static function getFacadeAccessor()
    {
        return AbcService::class;
    }
}

Now calling this code from the tink session (php artisan tink) outputs true, meaning that the attr value did not change in the constructor.

use AppHttpAbc;
Abc::partialMock();
Abc::shouldReceive('bMethod')->once()->andReturn('partialMock');
print_r(Abc::aMethod());

I’ve placed a dd in the constructor after changing the value of attr and we know after calling the Abc::partialMock() the constructor executed. Is this the normal behavior of the partialMock in the Facade? How can I only mock the bMethod method and use other part of the class without changes?

Number to Excel column name conversion

In Excel, column names are characters from A to Z, if there are more columns needed, it continues with AA, AB ...

I want to write a function, that converts integers to those excel column names.

0 .... A
25 ... Z
26 ... AA

The solution I came up with is working up to AZ, but I want it to work further.

function indexToXlxsColumn($index, $prefix="")
{
    if($index < 26)
    {
        return $prefix.chr($index+65);
    }else{
        return indexToXlxsColumn($index % 26, "A");
    }
}

How to adapt this function to work for each index without producing spaghetti code?

why pagniate_links not working any more in wordpress

paginate links shows a whitespace in my website i stuck for 2 days and the issue didn’t resolve

my code in function.php

function pagination_bar(){
   global $wp_query;

   $big = 999999999; // need an unlikely integer
    
   echo paginate_links( array(
       'base'    => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
       'format'  => '?paged=%#%',
       'current' => max( 1, get_query_var('paged') ),
       'total'   => $wp_query->max_num_pages
   ) );
}

my function call in index.php

<?php pagination_bar();?>

please Help??

How to integrate api platform with symfony

I am using the Platform API framework with fresh Symfony installation.

composer require api
composer require webonyx/graphql-php

in debug routes
php bin/console debug:router
I got :

  • api_entrypoint ANY ANY ANY /api/{index}.{_format}
  • api_doc ANY ANY ANY /api/docs.{_format}
  • api_graphql_entrypoint ANY ANY ANY /api/graphql
  • api_graphql_graphiql ANY ANY ANY /api/graphql/graphiql
  • api_graphql_graphql_playground ANY ANY ANY /api/graphql/graphql_playground

but nothing work (no api platform interface).

Any help?

Select last 7 days records by date and avoid duplicates by specific column

I’m pretty sure the problem I’m facing is quite small, but I can’t figure out what’s wrong.

I have the following table in my sql:

+-----+------------------+---------------------+
| ID  | EMAIL            | VISIT               |
+-----+------------------+---------------------+
| 1   | [email protected]   | 2021-04-01,13:20:23 |
| 2   | [email protected]  | 2021-04-03,12:03:44 |
| 3   | [email protected] | 2021-04-04,13:21:12 |
| 4   | [email protected]   | 2021-04-06,09:34:31 |
| 5   | [email protected]  | 2021-04-07,11:20:22 |
+-----+------------------+---------------------+

I want to display the last 7 days records but ordered by newest date and showing only the newest record by each email, like this

+-----+------------------+---------------------+
| ID  | EMAIL            | VISIT               |
+-----+------------------+---------------------+
| 3   | [email protected] | 2021-04-04,13:21:12 |
| 4   | [email protected]   | 2021-04-06,09:34:31 |
| 5   | [email protected]  | 2021-04-07,11:20:22 |
+-----+------------------+---------------------+

I’ve tried this query to achieve this:

Attempt 1: SELECT * FROM table WHERE VISIT BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW() GROUP BY EMAIL ORDER BY VISIT DESC

Attempt 2: SELECT DISTINCT (EMAIL) FROM table WHERE VISIT BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW() ORDER BY VISIT DESC

The results are displayed correctly, but in a strange order.
If I give up GROUP BY clause, it displays correctly but also includes EMAIL column duplicates.

How to return to the DOM a string variable from controller that contains an html image tag with asset() function in src ? [laravel 9][php 8]

I am facing an issue with laravel 9.
In my controller, I have created a variable wich contains inside quotes the html code to be returned to the view.

I have a problem to determine where I should use single quotes and double quotes or backticks so that the {{asset()}} in the image src is compiled properly.

for now my image url looks like this in the console :
http://127.0.0.1:8000/%7B%7B%20asset(storage/upload/test2-png.png)%20%7D%7D

Here is the error in the console :

GET http://127.0.0.1:8000/%7B%7B%20asset(storage/upload/test2-png.png)%20%7D%7D 404 (Not Found)

Here is the variable I am talking about :

$celebrityDetailsContent = "
                <div id='celebrity_text_and_picture_container' class='w-100 p-3'>
                    <img src='{{ asset(storage/upload/{$celebrityClicked->image}) }}' class='float-start img-border-radius img-thumbnail w-50 m-3' alt='Celebrity photo' title='Celebrity photo'>
                    <p class='fw-bold'>{$celebrityClicked->firstname} {$celebrityClicked->lastname}</p>
                    <p class='text-start'>{$celebrityClicked->description}</p>
                </div>
            ";

            return $celebrityDetailsContent; ```


Thanks for your Help.

The view is not displaying returned data *LIST* from the controller ( PHP – JQUERY )

I want to send a list ($data = [“1″,”2”];) to the controller from the view, and the result (1 2) be shown on the console,
but my code shows the code source of the view page! not the list $data

CHECK THE IMAGE:

Result Here Check

MY CODE :

———

Controller:

public function deliverySetup(){
      if(isset($_POST['request'])){
        $request = $_POST['request'];
          if($request == 'deliverySetup'){
            $data = ["1","2"];
             $this->view("control/hajar", $data);    
         }  
      }
    }

View:

function deliverySetup(){
    $.post('<?php echo URLROOT ?>' + 'Scan/deliverySetup', {request: 'deliverySetup'}, function (data) {
      console.log(data);
    });
}

Attempt to assign property of non-object when updating the existing the record

I want to update some records from my table and if user has uploaded a picture, I need to upload it and update the seller_certificate_card as well.

Here is my code:

public function doStepTwo(Request $request, $id)
{
    $newSeller = Seller::where('id', $id)->update([
        'seller_first_name' => $request->fname_seller,
        'seller_last_name' => $request->lname_seller,
    ]);
    
    if($request->hasFile('upload_certificate'))
    {
        $destination_path = "public/images/sellers/$user_id";
        $image = $request->file('upload_certificate');
        $image_name = $image->getClientOriginalName();
        $path = $request->file('upload_shenasname')->storeAs($destination_path,$image_name);
        $newSeller->seller_certificate_card = $image_name;
        $newSeller->save();
    }
}

And the seller_certificate_card at the table has this structure:

seller_certificate_card varchar(255)

But I get this error:

Attempt to assign property ‘seller_certificate_card’ of non-object

So what’s going wrong here? How can I fix this issue?

PHP ftp_connect in readonly mode

There is a way to establish a read-only ftp connection with PHP?

I only need to do these inside the remote ftp:

  • ftp_connect
  • ftp_login
  • ftp_chdir
  • ftp_get
  • ftp_close

If I, for mistake, delete/modify something on the remote ftp it’ll be a very big problem (due to work matters).

(I already check my code 10 times and do a lot of tests, but human error is always possible.)

Thanks

php calculation keeps getting the answer as 0

this is the index.php file

if(isset($_POST['submit']))
{
    echo header('Location:answer.php');
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="container">
        <form method="post">
            <div class="form-group">
                <label> Insert P value </label>
                <input type="text" name="p" placeholder="please insert your P value">
</div>
<br>

<div class="form-group">
    <label> Insert R value </label>
    <input type="text" name="r" placeholder ="please insert your R value ">
    
</div>
<br>
<div class="form-group">
    <label> Insert your N value </label>

    <input type="text" name="n" placeholder=" please insert your N value">

</div>
<br>
    <button type="submit" name="submit" > Submit </button>
</body>
</html>

this is the answer.php file

<?php

$p=isset($_POST['p'])?$_POST['p']: " ";
$r=isset($_POST['r'])?$_POST['r']:" ";
$n=isset($_POST['n'])?$_POST['n']: " ";
$si=(int)$p*(int)$r*(int)$n/100;
echo "Hello this is the final answer ".$si;
?>

i want the answer to be displayed in another page that is answer.php but whatever number i am inserting i keep getting the answer as 0. Please help and thank you.

how to put an array paramter in a sql command?

       $stmt = $conn->prepare("UPDATE stopwatch SET $array[0] = ...... 
      $stmt->execute();

doing $array[0] works fine in my sql command, but i want an variable in my array parameter like $array[$value] doing this doesn’t work.

To explain a bit i want to do an sql commmand that use a php get methode and the variable that i get from the get methode i want to put in an array like that:

$value = $_GET['value']; // value = 2 for example
$ID = array("t_inter_1", "t_inter_2", "t_inter_3", "t_arrivee");

    echo $ID[$_GET['value']]; // works fine
    echo $ID[$value]; // works fine

but doing this in my sql command doesn’t work. I don’t know what am i supposed to do, and I don’t know what I am doing wrong, thanks for the help

How do I redirect the number of rows after a search?

I want to show the number of search results if there are and if not, I want to show a message that there are no results for your search

controller

 public function search(Request $request){
        $search = $request->get('search');
        $Airline['Airlines'] = DB::table('airlines')->where(DB::raw("CONCAT(id,' ',name,' ',country)"),'LIKE','%'.$search.'%')->paginate(4);
        $count = count($Airline);
        if ($count>0) {
         return redirect()->view('admin.airline',$Airline,)->with('success',$count.' records found');

        }
        else{
            return redirect()->view('admin.airline',$Airline)->with('error','No record found');
        }
        
    }

airline.blade.php

             @if(session()->has('success'))
                <div class="alert alert-success">
                    {{ session()->get('success') }}
                </div>
            @endif
            @if(session()->has('error'))
                <div class="alert alert-danger">
                    {{ session()->get('error') }}
                </div>
            @endif

PHP – Optimise read write time

I am reading 200MB of CSV file with 1344953 rows then filtering and writing into other 18 files and all within 25 seconds, but someone in my class has done it under 8 seconds.

Here is my code:

<?php    
$sid = array (
    "188" => "188",
    "203" => "203",
    "206" => "206",
    "209" => "209",
    "213" => "213",
    "215" => "215",
    "228" => "228",
    "270" => "270",
    "271" => "271",
    "375" => "375",
    "395" => "395",
    "452" => "452",
    "447" => "447",
    "459" => "459",
    "463" => "463",
    "481" => "481",
    "500" => "500",
    "501" => "501"
);
$Separator = ',';
array_map('unlink', glob("data_*.csv"));
$fp = fopen("fragment_org.csv", "r");
while (($line = stream_get_line($fp, 0, "n")) !== false) {
    $data = explode(";",$line);
    $siteID = $data[4];
    $ts = $data[0];
    $nox = $data[1];
    $no2 = $data[2];
    $no = $data[3];
    $pm10 = $data[5];
    $nvpm10 = $data[6];
    $vpm10 = $data[7];
    $nvpm25 = $data[8];
    $pm25 = $data[9];
    $vpm25 = $data[10];
    $co = $data[11];
    $o3 = $data[12];
    $so2 = $data[13];
    $loc = $data[17];
    $latlong = $data[18];
    $latlong_ext = explode(",",$latlong);
    $lat = $latlong_ext[0];
    $long = $latlong_ext[1];
    $wrr = array( $siteID, $ts, $nox, $no2, $no, $pm10, $nvpm10, $vpm10, $nvpm25, $pm25, $vpm25, $co, $o3, $so2, $loc, $lat, $long );
    if($siteID == $sid[$siteID]) {
        $fip = fopen('data_'.$siteID.'.csv', 'a');
        if(!$nox == "" || !$co == "") {
            fputs($fip, implode($Separator,$wrr).PHP_EOL);
        }
        fclose($fip);
    }
}
fclose($fp);

Much of the time is taking when writing to multiple files i.e., $fip becasue it is working faster if I am writing everything to a single file.

Can someone kindly guide me on how to optimize it more. Someone said to me this, “Simply read a line and write it out to a specific file. Avoid opening and closing lots of files repeatedly (very time consuming).” , but I am doing that.

Here is what the CSV file that I am reading looks like:
First 5 lines from CSV

Thanks for your time and looking into it.

Insert a text mixed with double and single quotes into the sql database

I have a form and I let users type some additional details for the form. What if the user enters a text mixed with single and double quotes.

ex:- I’d like to join. So we”are party”this”time’addtional’details`willbe”

I found out that, because of this text, nothing goes into the database. It means literally this thing crashes my whole program.

How do I enter it into the database using PHP or MySQL query?

I’ve tried these methods

  • Backslashes (‘)

  • JSON encode

  • str_repalce

  • htmlspecialchars with ENT_QUOTES

But nothing works for me!