How to write unit test for code calling a class from a library with static variable and constructor?

I am writing some unit test for some legacy code as a preparation for some refactoring. One section of the code is calling a class from a library where I cannot change the code in it. The code is using its constructor and calling some static variable. May I ask how can I mock the method for testing? (or how do I test the method without mocking?)

I have tried to simplify my code for an example:

<?php
//This is from the library code that I am unable to change
class ResponseMessage {
    const STATUS_ERROR = 500;
    const STATUS_SUCCESS = 200;

    function __construct( $responseMessage, $responseCode ) {
        $this->responseMessage = $responseMessage;
        $this->responseCode = $responseCode
    }
    
    public function sendMessage($sendToAdmin = false) {
        // Some code to send email and trigger some API to notice other service, so this needed to be mocked in unit test to stop it. It is also needed to check if this function is actually called.
    }
    
    //.... Some other methods and variables
}

///////////////////////////////////////////////////////////////////
//This is my class to be tested. If possible I would like to avoid changing any code, but if it is necessary this code can be changed a bit for injecting mock class.
class myClass {
    // ... some other methods where I have no problem testing....
    function handle($input) {
        //The actual comparision is much more complicated. Simplified for this question
        if (empty($input)) {
            // Some other error handling, no response message is generated
            return;
        }
        if ( $input == 1 )
            $responseMessage = new ResponseMessage('The input is 1', ResponseMessage::STATUS_SUCCESS );
        else if ( $input == 2 )
            $responseMessage = new ResponseMessage('The input is 2', ResponseMessage::STATUS_SUCCESS );
        else
            $responseMessage = new ResponseMessage('Unexpected input', ResponseMessage::STATUS_ERROR );
        
        $respnoseMessage->sendMessage();

        $responseMessageToAdmin = new ResponseMessage('The comaparison is triggered', RespnoseMessage::STATUS_SUCCESS);
        $responseMessageToAdmin->sendMessage(true);
    }
}
///////////////////////////////////////////////////////////////////
//This is my testing class in PHPUnit.
class testMyClass {
    public function testProcessWithInputOne {
        // how should I mock ResponseMessage here?
        $myClass = new MyClass();
        $myClass->handle(1);
    }
}

How to restrict an end user to login only at one device at a time in Laravel

I have developed an application using Laravel 9 and I want to restrict my endusers to login only at a single device at one time. The end user should not shares his user id and password with other users and login both at one time.

How can I restrict the end user login if same user credentials are already logged in from other machine or location or device??

I did try to save current session id in db with last timestamp of login and delete that same when end user logout. in this case if end user do not logout my previous session does not expire

Error: Unauthenticated I am using Tenancy for Laravel as Single Domain and Multi-Database with Sanctum API

Problem: {“message”:”Unauthenticated.”}

Explanation: I am using Tenancy for Laravel, having single central domain, but with multi database. Each database has personal_access_token table where I am storing the data. There is a 6 digit code organisation code for each organisation and minimum 8 digit user code for each user. User can only login through the usercode. On the time of login I can easily access the tenant data by having the organisation code and can store the token in the personal_access_token table for that particular database. But after the token generate I can not able to authenticate the user

Expectation: Validating the token and get the user info and the set the user’s tenant for the future tasks on the particular database.

api.php

Route::post('/login', [UserController::class, 'login']);

Route::middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [UserController::class, 'logout']);
    Route::post('/create-new-user', [UserController::class, 'store']);
});

login code

public function login(Request $request): mixed
    {
        $request->validate([
            'username' => 'required',
            'password' => 'required'
        ]);
        try {
            $userCode = (int)(substr($request->username, 3));
            $organisationCode = (int)(substr($request->username, 3, 6));

            $tenant = Tenant::find($organisationCode);
            Tenancy::initialize($tenant);
            
            $user = User::where('users.userCode', $userCode)
                ->join('organisation_infos', 'organisation_infos.code', '=', 'users.organisationCode')
                ->select('users.*', 'organisation_infos.centreName')
                ->first();

            if (!$user || !Hash::check($request->password, $user->password)) {
                return APIResponseHelper::ApiResponse(
                    isError: false,
                    responseCode: 4701,
                    responseMessage: "Invalid Username or Password.",
                    responseContent: "Invalid Username or Password."
                );
            }

            if ($user->loggedIn === 1) {
                return APIResponseHelper::ApiResponse(
                    isError: false,
                    responseCode: 4702,
                    responseMessage: "User Already Logged in on another device.",
                    responseContent: "User Already Logged in on another device."
                );
            }

            $user->loggedIn = true;
            $user->save();

            $token = $user->createToken($user->organisationCde . $user->name . $user->mobile . 'Rizwan' . $user->userCode)->plainTextToken;

            Tenancy::end();

            return APIResponseHelper::ApiResponse(
                isError: false,
                responseCode: 4700,
                responseMessage: "Successfully Logged In.",
                responseContent: ["token" => $token, "createdUserInfo" => $user]
            );
        } catch (Exception $exception) {
            $getTheErrorMessage = $exception->getPrevious();
            return APIResponseHelper::ApiResponse(
                isError: false,
                responseCode: 4713,
                responseMessage: "Error Occurs",
                responseContent: $getTheErrorMessage->errorInfo[2] ?? 'Contact Core Team'
            );
        }
    }

logout code php

public function logout(): mixed
    {
        $userInfo = auth()->user();
        dd($userInfo->organisationCode);
        $tenant = Tenant::find($userInfo->organisationCode);
        Tenancy::initialize($tenant);
        return APIResponseHelper::ApiResponse(
            isError: false,
            responseCode: 4700,
            responseMessage: "Logout Message",
            responseContent: "Logout Content"
        );
    }

I am getting this.

I have tried to overcome this problem but I failed each time. Now I am expecting a solution from PHP or Developer community.

problem running html or php code in visual studios

I was able to run my codes normally on vs. But after intalling some php package its not running or debugging my code instead an error dialogue box keeps popping up everytime I run a code. It says “php executable not found. Install php and add it to your path or set the php.debug.executablepath setting.”
Also it opens a new tab on chrome whenever I run a code which displays nothing but error “try reload this page”.
It has url as “localhost:8000”.

i tried uninstalling some extensions but it didnt help.
I expect it to run smoothly as it was earlier.

Is there any solution to this issue [closed]

I hosted a website some months ago, it works well but now when I try to login I will see something like “this page can’t be reached” please what could be the issue.
The index file still works but when I click the login button I get an error message.

Chart JS not displaying bars/labels on graph

I am using Laravel 10, and Chart.JS for graphs on my site.

I’ve got the stats loaded from the database, however, when creating the graph it shows me (https://i.stack.imgur.com/QT0s7.jpg) the graph lines, and the numbers up the side correctly but no bars or labels.

To get the information:

$stats = UserCountStats::query()
            ->start(now()->subMonths(2))
            ->end(now()->subSecond())
            ->groupByWeek()
            ->get();

My code to generate the graph:

<script>
        // Retrieve the statistical data from laravel-stats
        var statsData = {!! json_encode($stats) !!};

        // Process the data and create the chart
        var labels = statsData.map(stat => stat.period);
        var values = statsData.map(stat => stat.value);

        // Create the Chart.js bar chart
        var ctx = document.getElementById('userCountChart').getContext('2d');
        var userCountChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'User Count',
                    data: values,
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderColor: 'rgba(75, 192, 192, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    x: {
                        grid: {
                            display: true
                        }
                    },
                    y: {
                        beginAtZero: true // Ensure the y-axis starts at 0
                    }
                },
                plugins: {
                    legend: {
                        display: false // Hide the legend
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'User Count: ' + context.parsed.y;
                            }
                        }
                    }
                }
            }
        });
    </script>

Stats passed
[{“start”:”2023-06-05T00:00:00.000000Z”,”end”:”2023-06-12T00:00:00.000000Z”,”value”:0,”increments”:0,”decrements”:0,”difference”:0},{“start”:”2023-06-12T00:00:00.000000Z”,”end”:”2023-06-19T00:00:00.000000Z”,”value”:0,”increments”:0,”decrements”:0,”difference”:0},{“start”:”2023-06-19T00:00:00.000000Z”,”end”:”2023-06-26T00:00:00.000000Z”,”value”:0,”increments”:0,”decrements”:0,”difference”:0},{“start”:”2023-06-26T00:00:00.000000Z”,”end”:”2023-07-03T00:00:00.000000Z”,”value”:0,”increments”:0,”decrements”:0,”difference”:0},{“start”:”2023-07-03T00:00:00.000000Z”,”end”:”2023-07-10T00:00:00.000000Z”,”value”:0,”increments”:0,”decrements”:0,”difference”:0},{“start”:”2023-07-10T00:00:00.000000Z”,”end”:”2023-07-17T00:00:00.000000Z”,”value”:0,”increments”:0,”decrements”:0,”difference”:0},{“start”:”2023-07-17T00:00:00.000000Z”,”end”:”2023-07-24T00:00:00.000000Z”,”value”:0,”increments”:0,”decrements”:0,”difference”:0},{“start”:”2023-07-24T00:00:00.000000Z”,”end”:”2023-07-31T00:00:00.000000Z”,”value”:4,”increments”:4,”decrements”:0,”difference”:4},{“start”:”2023-07-31T00:00:00.000000Z”,”end”:”2023-08-07T00:00:00.000000Z”,”value”:7,”increments”:3,”decrements”:0,”difference”:3},{“start”:”2023-08-07T00:00:00.000000Z”,”end”:”2023-08-14T00:00:00.000000Z”,”value”:11,”increments”:4,”decrements”:0,”difference”:4}]

I’ve tried for a while, and can’t figure this out.

How Do I Get Attribute Value in WooCommerce?

Recently, I installed a plugin that send the order details to WhatsApp, I did some changes on this to fit more for that I need, but now I have a problem and no ideia how to resolve, basically I need the attribute name and value in this message as well I tried many ways and nothing work.

Someone know how how can I get the attribute name and valeu from a product?

Redirecting favicoin file in root directory gives a 404 error

I have added favicon.ico to root dir. There is WP installed on my site, and all the permalinks are set to have “/” trailing slash appear at the end. Now I want to achieve the same with favicon.ico.

This is the code I am using in my .htaacess but it is returning 404 error.

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/favicon.ico$

RewriteRule ^(.*)$ /favicon.ico/ [L,R=301]

Any help?

Not sure why it returns such an error instead of just putting / at the end of the URL.

how to configure SQL Server With php 8.2 on iis Server

<?php
if($_REQUEST['tablename'])
{
    $servername="New-3\SQLEXPRESS";
    $database="mydb"; $uid='',
    $passw="";

    // Create database connection
    try {
            $conn = new PDO (sqlsrv:Server=$servername,Database=$database, $uid, $passw);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } 
    catch (PDOException $e) 
    {
        die ("Error connecting to SQL Server: ". $e->getMessage());

    }
}
?>

this code gives error

Error connecting to SQL Server: SQLSTATE [08001]: [Microsoft] [ODBC Driver 17 for SQL Server] Named Pipes Provider: Could not open a connection to SQL Server [53].

PHP: CakePHP call to undefined function when importing it from a different Namespace

I’m quite new to PHP and Namespacing. I’m trying to use cakePHP to develop a website and i’m stuck with a problem regarding the use of a function imported from a different namespace.

the problem is the following:

I’ve defined a Class inside a proper namespace called AppPlanner.
The class file is also called Planner.php and it’s locate under src/Planner/Planner.php

<?php

namespace AppPlanner;


class Planner
{
   public static function myfunc(){}


}

Then I’ve got my controller called ChallengesControllerdefined as a class inside a file also called ChallengesController.php under src/Controller/ChallengesController.php which has it’s own namespace AppController. Here I’ve done the following:

<?php
declare(strict_types=1);

namespace AppController;
\ some more imports
use AppPlannerPlanner;

class ChallengesController extends AppController
{

  public function doThings(){
       $res = Planner::myfunc();
  }

}

Now when i call the endpoint /challenges/doThings it reaches the line when i call the function but then gives the following error (i’m using Xdebug to debug):

message = "Call to undefined function AppPlannerknapSolveFast2()"
file = "/var/www/myapp/src/Planner/Planner.php"

my composer.json autoload is set as follow:

 "autoload": {
        "psr-4": {
            "App\": "src/"
        }
    },

can anybody explain to me what i’m missing?

thanks

Google Assistant API Integration [closed]

I went to https://console.cloud.google.com/ and enabled the google assistant API. After that I went to the credentials part, created a service account and downloaded the JSON file containing the login credentials. I have also generated an API key, but I cannot get the proper code to call the Google Assistant API from my PHP file on my local machine. Can anyone provide me with the code? You can also provide the code in node.js.

I tried some solutions which I obtained from ChatGPT and Google Bard, where I installed the google/apiclient library but whatever code I got from there gave me error.

Script to redirect to a page and return to the same page – php

I have two sites I have a question if I can make when a visitor enters my site after a certain period of browsing when he clicks on any link inside the first site he turns it on a page on the second site that counts to 10 seconds and then returns to the page that he clicked on in the first site and this is repeated The status every specific period is mentioned inside the code .

not able to connect to sms gateway using curl in php

I have a website done in codeigniter php, where I want to send sms to user, the plain php curl is working fine in phpsanbox or on my local, now I added it to my codeigniter model like below:

public function sendOtptoCustomer($mobile,$customerMessage,$temp_id){
    $url = "http://dstri.connectbind.com:8443/sendsms/bulksms?username=xxxxx&password=xxxxx&type=0&dlr=1&destination=".$mobile."&source=xxxx&message=".$customerMessage."&entityid=xxxx&tempid=".$temp_id;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

    $response = curl_exec($ch);


    if (curl_errno($ch)) {
        $error_message = curl_error($ch);
        var_dump($error_message); 
    } 

    curl_close($ch);
}

Here i am getting the following error:

string(72), failed to connect to dstri.connectbind.com port 8443 connection refused

Can anyone please tell me what could be wrong in here, thanks in advance