PHPUnit – catch message from Throwable class

In my Symfony project, I am writing tests. I wrote all tests that are covering my CustomException. But, I want to write separate test to catch the one with Throwable. But, as all my cases are covered with CustomException, I do not know the way how to write a tests that will catch the message in Throwable.

From Controller:

 /**
 * @Route("/endpoint", methods={"POST"}, name="endpoint_name")
 */
public function someMethod($uuid)
 try {
        $this->myService->someServiceMethod($id);
        return $this->success("SUCCESS");
    } catch (CustomException $e) {
        return $this->handleCustomException($e);
    } catch (Throwable $e) {
        $this->logger->error("FAILED: " . $e->getMessage(), [
            $id
        ]);
        return $this->error("FAILED");
    }

Any thoughts?

public function testSomeMethod(): void
{
    $this->client->request(
        Request::METHOD_POST,
        self::API_URL . self::POST_ENDPOINT,
        [],
        [],
        [
            'CONTENT_TYPE' => 'application/json',
            'ACCEPT' => 'application/json',
        ]
    );

    $response = $this->client->getResponse();
    $responseBody = json_decode($response->getContent(), true);

    $this->assertContains('Some message from Custom Exception!', $responseBody['error']);
    $this->assertEquals(405, $response->getStatusCode());
}

This is the test for my Custom Exception that is working.
Is there any way I can wrote the same test but to catch the message from Throwable class.

Free Payment gateway method in php for Pakistan

I am from Pakistan,
I developed an ecommerce website for final year project, now I want to integrate some payment gateway like easypisa ,jazzcash, I don’t know which payment gateway is available in Pakistan and free because am student i use only for testing , and which one is the best to be used in Pakistan. If someone already have an experience of using some payment gateway in Pakistan,
please let me know.

cPanel MySQL, Database Err: SQLSTATE[HY000] [1044] Access denied for user ‘MySQL DB name’ to database ‘MySQL user name’

I applied a free domina xxx.freewebhostforyou.ml
then i uploaded my sites files through ftp,
when i comleted the mysql set, then came to
https://i.stack.imgur.com/mlalN.jpg
Database Err: SQLSTATE[HY000] [1044] Access denied for user ‘htofo_30627431’@’192.168.%’ to database ‘htofo_30627431’

This is my MySQL setting
‘htofo_30627431’@’192.168.%’ is ‘htofo_30627431’@’local%’,
but where is ‘htofo_30627431_yang’ I set?
https://i.stack.imgur.com/v4oKj.jpg

Since it is a free host/domina, it doesn’t support SSH.

How should solve it in MySql of cPanel?

Tks

Testing Symfony validation with Panther

I’m testing my validations and I send wrong values in all my input :

$crawler = $this->client->getCrawler();

        $form = $crawler->selectButton('Créer')->form();

        $form->setValues([
            'Contractor[lastName]' => str_repeat('maxLength', self::OVER_MAX_LENGTH,),
            'Contractor[firstName]' => str_repeat('maxLength', self::OVER_MAX_LENGTH,),
            'Contractor[email]' => str_repeat('maxLength', self::OVER_MAX_LENGTH,).'@society.com',
            'Contractor[phone]' => str_repeat('0', self::UNDER_MIN_LENGTH,),
            'Contractor[password][password][first]' => 'first',
            'Contractor[password][password][second]' => 'second',
            'Contractor[status]' => 'admin.crud.user.field.choices.boss'
        ]);

        $this->client->submitForm('Créer');

        $this->client->waitFor('.invalid-feedback');
        $this->client->waitForVisibility('.invalid-feedback');

        $this->client->takeScreenshot('add.png');

        $totalErrors = $crawler->filter('div.invalid-feedback')->count();
        $errorExpected = 5;

        $this->assertNotCount($totalErrors, [$errorExpected]);

When I test I ask to wait until the errors are displayed. Then I count the number of errors and I compare. The problem is when this line is test $totalErrors = $crawler->filter('div.invalid-feedback')->count(); I’ve got an error which say :
FacebookWebDriverExceptionStaleElementReferenceException: stale element reference: element is not attached to the page document.
In the screenshot, the errors are displayed.
I really don’t understand why because I asked to wait for the element to be in the DOM and I had no errors.
Any idea ?

TypeError Argument 1 passed to ShopifyUtils::sanitizeShopDomain() must be of the type string,

I getting below error,

TypeError
Argument 1 passed to ShopifyUtils::sanitizeShopDomain() must be of the type string, null given, called in /var/www/html/shopiapp/test_me/routes/web.php on line 29
http://127.0.0.1:8081/ 

enter image description here

enter image description here

web.php

<?php

use AppModelsSession;
use IlluminateHttpRequest;
use IlluminateHttpResponse;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesRoute;
use ShopifyAuthOAuth;
use ShopifyAuthSession as AuthSession;
use ShopifyClientsHttpHeaders;
use ShopifyClientsRest;
use ShopifyContext;
use ShopifyUtils;
use ShopifyWebhooksRegistry;
use ShopifyWebhooksTopics;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::fallback(function (Request $request) {
$shop = Utils::sanitizeShopDomain($request->query('shop')); //this line shows the error...
$host = $request->query('host');
$appInstalled = Session::where('shop', $shop)->exists();
if ($appInstalled) {
return view('react', [
'shop' => $shop,
'host' => $host,
'apiKey' => Context::$API_KEY
]);
}
return redirect("/login?shop=$shop");
});

Route::get('/login/toplevel', function (Request $request, Response $response) {
$shop = Utils::sanitizeShopDomain($request->query('shop'));

$response = new Response(view('top_level', [
'apiKey' => Context::$API_KEY,
'shop' => $shop,
'hostName' => Context::$HOST_NAME,
]));

$response->withCookie(cookie()->forever('shopify_top_level_oauth', '', null, null, true, true, false, 'strict'));

return $response;
});

Route::get('/login', function (Request $request) {
$shop = Utils::sanitizeShopDomain($request->query('shop'));

if (!$request->hasCookie('shopify_top_level_oauth')) {
return redirect("/login/toplevel?shop=$shop");
}

$installUrl = OAuth::begin(
$shop,
'/auth/callback',
true,
['AppLibCookieHandler', 'saveShopifyCookie'],
);

return redirect($installUrl);
});

Route::get('/auth/callback', function (Request $request) {
$session = OAuth::callback(
$request->cookie(),
$request->query(),
['AppLibCookieHandler', 'saveShopifyCookie'],
);

$host = $request->query('host');
$shop = Utils::sanitizeShopDomain($request->query('shop'));

$response = Registry::register('/webhooks', Topics::APP_UNINSTALLED, $shop, $session->getAccessToken());
if ($response->isSuccess()) {
Log::debug("Registered APP_UNINSTALLED webhook for shop $shop");
} else {
Log::error(
"Failed to register APP_UNINSTALLED webhook for shop $shop with response body: " .
print_r($response->getBody(), true)
);
}

return redirect("?" . http_build_query(['host' => $host, 'shop' => $shop]));
});

Route::post('/graphql', function (Request $request) {
$response = Utils::graphqlProxy($request->header(), $request->cookie(), $request->getContent());

$xHeaders = array_filter(
$response->getHeaders(),
function ($key) {
return str_starts_with($key, 'X') || str_starts_with($key, 'x');
},
ARRAY_FILTER_USE_KEY
);

return response($response->getDecodedBody(), $response->getStatusCode())->withHeaders($xHeaders);
})->middleware('shopify.auth:online');

Route::get('/rest-example', function (Request $request) {
/** @var AuthSession */
$session = $request->get('shopifySession'); // Provided by the shopify.auth middleware, guaranteed to be active

$client = new Rest($session->getShop(), $session->getAccessToken());
$result = $client->get('products', [], ['limit' => 5]);

return response($result->getDecodedBody());
})->middleware('shopify.auth:online');

Route::post('/webhooks', function (Request $request) {
try {
$topic = $request->header(HttpHeaders::X_SHOPIFY_TOPIC, '');

$response = Registry::process($request->header(), $request->getContent());
if (!$response->isSuccess()) {
Log::error("Failed to process '$topic' webhook: {$response->getErrorMessage()}");
return response()->json(['message' => "Failed to process '$topic' webhook"], 500);
}
} catch (Exception $e) {
Log::error("Got an exception when handling '$topic' webhook: {$e->getMessage()}");
return response()->json(['message' => "Got an exception when handling '$topic' webhook"], 500);
}
});

Utils.php

<?php

declare(strict_types=1);

namespace Shopify;

use ShopifyContext;
use ShopifyAuthOAuth;
use ShopifyAuthSession;
use ShopifyClientsGraphql;
use ShopifyClientsHttpResponse;
use ShopifyExceptionInvalidArgumentException;
use ShopifyExceptionSessionNotFoundException;
use FirebaseJWTJWT;

/**
* Class to store all util functions
*/
final class Utils
{
/**
* Returns a sanitized Shopify shop domain
*
* If the provided shop domain or hostname is invalid or could not be sanitized, returns null.
*
* @param string $shop A Shopify shop domain or hostname
* @param string|null $myshopifyDomain A custom Shopify domain
*
* @return string|null $name a sanitized Shopify shop domain, null if the provided domain is invalid
*/
public static function sanitizeShopDomain(string $shop, ?string $myshopifyDomain = null): ?string
{
$name = trim(strtolower($shop));

$allowedDomainsRegexp = $myshopifyDomain ? "($myshopifyDomain)" : "(myshopify.com|myshopify.io)";

if (!preg_match($allowedDomainsRegexp, $name) && (strpos($name, ".") === false)) {
$name .= '.' . ($myshopifyDomain ?? 'myshopify.com');
}
$name = preg_replace("/A(https?://)/", '', $name);

if (preg_match("/A[a-zA-Z0-9][a-zA-Z0-9-]*.{$allowedDomainsRegexp}z/", $name)) {
return $name;
} else {
return null;
}
}

/**
* Determines if the request is valid by processing secret key through an HMAC-SHA256 hash function
*
* @param array $params array of parameters parsed from a URL
* @param string $secret the secret key associated with the app in the Partners Dashboard
*
* @return bool true if the generated hex digest is equal to the hmac parameter, false otherwise
*/
public static function validateHmac(array $params, string $secret): bool
{
$hmac = $params['hmac'] ?? '';
unset($params['hmac']);

$computedHmac = hash_hmac('sha256', http_build_query($params), $secret);

return hash_equals($hmac, $computedHmac);
}

/**
* Retrieves the query string arguments from a URL, if any
*
* @param string $url The URL string with query parameters to be extracted
*
* @return array $params Array of key/value pairs representing the query parameters or empty array
*/
public static function getQueryParams(string $url): array
{
$queryString = parse_url($url, PHP_URL_QUERY);
if (empty($queryString)) {
return [];
}
parse_str($queryString, $params);
return $params;
}

/**
* Checks if the current version of the app (from Context::$API_VERSION) is compatible, i.e. more recent, than the
* given reference version.
*
* @param string $referenceVersion The version to check
*
* @return bool
* @throws ShopifyExceptionInvalidArgumentException
*/
public static function isApiVersionCompatible(string $referenceVersion): bool
{
if (Context::$API_VERSION === 'unstable' || Context::$API_VERSION === 'unversioned') {
return true;
}

if (!ctype_digit(str_replace('-', '', $referenceVersion))) {
throw new InvalidArgumentException("Reference version '$referenceVersion' is invalid");
}

$currentNumeric = (int)str_replace('-', '', Context::$API_VERSION);
$referenceNumeric = (int)str_replace('-', '', $referenceVersion);

return $currentNumeric >= $referenceNumeric;
}

/**
* Loads and offline session
* No validation is done on the shop param; ensure it comes from a safe source
*
* @param string $shop The shop URL to find the offline session for
* @param bool $includeExpired Optionally include expired sessions, defaults to false
*
* @return Session|null If exists, the most recent session
* @throws ShopifyExceptionUninitializedContextException
*/
public static function loadOfflineSession(string $shop, bool $includeExpired = false): ?Session
{
Context::throwIfUninitialized();

$sessionId = OAuth::getOfflineSessionId($shop);
$session = Context::$SESSION_STORAGE->loadSession($sessionId);

if ($session && !$includeExpired && !$session->isValid()) {
return null;
}

return $session;
}

/**
* Loads the current user's session based on the given headers and cookies.
*
* @param array $rawHeaders The headers from the HTTP request
* @param array $cookies The cookies from the HTTP request
* @param bool $isOnline Whether to load online or offline sessions
*
* @return Session|null The session or null if the session can't be found
* @throws ShopifyExceptionCookieNotFoundException
* @throws ShopifyExceptionMissingArgumentException
*/
public static function loadCurrentSession(array $rawHeaders, array $cookies, bool $isOnline): ?Session
{
$sessionId = OAuth::getCurrentSessionId($rawHeaders, $cookies, $isOnline);

return Context::$SESSION_STORAGE->loadSession($sessionId);
}

/**
* Decodes the given session token and extracts the session information from it
*
* @param string $jwt A compact JSON web token in the form of XXXX.yyyy.zzzz
*
* @return array The decoded payload which contains claims about the entity
*/
public static function decodeSessionToken(string $jwt): array
{
$payload = JWT::decode($jwt, Context::$API_SECRET_KEY, array('HS256'));
return (array) $payload;
}

/**
* Forwards the GraphQL query in the HTTP request to Shopify, returning the response.
*
* @param array $rawHeaders The headers from the HTTP request
* @param array $cookies The cookies from the HTTP request
* @param string $rawBody The raw HTTP request payload
*
* @return HttpResponse
* @throws PsrHttpClientClientExceptionInterface
* @throws ShopifyExceptionCookieNotFoundException
* @throws ShopifyExceptionMissingArgumentException
* @throws ShopifyExceptionSessionNotFoundException
* @throws ShopifyExceptionUninitializedContextException
*/
public static function graphqlProxy(array $rawHeaders, array $cookies, string $rawBody): HttpResponse
{
$session = self::loadCurrentSession($rawHeaders, $cookies, true);
if (!$session) {
throw new SessionNotFoundException("Could not find session for GraphQL proxy");
}

$client = new Graphql($session->getShop(), $session->getAccessToken());

return $client->proxy($rawBody);
}
}

I have tried to create a public app (PHP), and I get this error.
I’m Uses UBUNTU System,
how can I fix this?

hello developers, please help me with this, I don’t understand that where can I need to change? in the files,
because when I create an app using PHP the code is done by shopify-cli.

there is not any solution to this question?
please help me with this, I’m a beginner at Shopify, so need your bits of help.

Php session problems on live server [closed]

I have a blog site with admin panel. While i am logged in the admin panel if try to log in at different chrome window or incognito tab it logs in without asking username and password.
But when i try this at localhost it works perfect, sessions are okay. Is it working because it is local, or what is about?

Design pattern for share calculating order totals

I want to solve two problems:

  1. Share data between existing methods
  2. Less coupling this methods

What pattern I can use for calculating totals?

/** @var array $orderData */

// Ordered products total price
$orderedProductsTotal = $this->orderedProductsTotalPrice($orderData);

$total = $orderedProductsTotal;

// Shipping cost dependent on ordered products total price
$shippingCost = $this->shippingCost($orderedProductsTotal);
$total += $shippingCost;

// Client allowed credit, depends on ordered products total price
$total -= $this->credit($orderedProductsTotal);

// Available coupon depends on order data (i.e. special products in order, etc)
$total -= $this->coupon($orderData);

// Client personal discount applying on total amount, excluding shipping cost
$total -= $this->personalDiscount($total - $shippingCost);

I thinking about something like this

$calcs = [
    'OrderProductsCalc',
    'ShippingCalc',
    'CreaditCalc',
    'CouponCalc',
    'PersonalDiscountCalc',
];

$total = 0;


foreach ($calcs as $v) {
    // How to share data between calculators?
    // Separated calculated total values of each calculator
    // Order data
    // Something else
    /** @var CalculatorInterface $calculator */
    $calculator = $this->container->get($v);
    $total = $calculator->getTotal($total);
}

This is a simple class dependents on Cart items

class OrderProductsCalc implements CalcInterface
{
    private Cart $cart;

    public function __construct(Cart $cart)
    {
        $this->cart = $cart;
    }

    public function getTotal(float $total): float
    {
        $subTotal = $this->cart->getTotal();

        return $total + $subTotal;
    }
}

ShippingCalc is simple too as it run next to OrderProductsCalc.

But CreaditCalc::getTotal() should receive as $total the $subTotal inner value from OrderProductsCalc::getTotal().

class CreaditCalc implements CalcInterface
{
    private $customer;

    public function __construct(Customer $customer)
    {
        $this->customer = $customer;
    }

    /**
     * @var float $total The $subTotal inner value from OrderProductsCalc::getTotal()
     */
    public function getTotal(float $total): float
    {
        $balance = $this->customer->getBalance();
        if ($balance) {
            $credit = min($balance, $total);
            
            if ($credit > 0) {
                $total -= $credit;
            }
        }
        
        return $total;
    }
}

PHP websocket on synology

I would like to create a chat server placed on my Nas Synology DS212J accessible by internet. I am not very competent in the field but I understood that it was necessary to use “websocket”. I tried with Node.js but my nas does not allow me to install a fairly recent Node version apparently. So I am looking at “PHP Websocket”.
I managed to find a code on: https: //github.com/Flynsarmy/PHPWebSocket-Chat which I deposited in the / web / chatLogPat folder of my Nas.
I managed to launch server.php in SSH but when I connect to my Chat page, I cannot establish a connection … Putty (ssh) tells me all the time: “myconnectionIp has disconnected

Can you help me please?

my link to index.html is: https://serveurarchaux.synology.me/chatLogPat

My NAS is connected to my box in: 192.168.1.12

Here are my files:

server.php on web/chatLogPat

    <?php
// prevent the server from timing out
set_time_limit(0);

// include the web sockets server script (the server is started at the far bottom of this file)
require 'class.PHPWebSocket.php';

// when a client sends data to the server
function wsOnMessage($clientID, $message, $messageLength, $binary) {
    global $Server;
    $ip = long2ip( $Server->wsClients[$clientID][6] );

    // check if message length is 0
    if ($messageLength == 0) {
        $Server->wsClose($clientID);
        return;
    }

    //The speaker is the only person in the room. Don't let them feel lonely.
    if ( sizeof($Server->wsClients) == 1 )
        $Server->wsSend($clientID, "There isn't anyone else in the room, but I'll still listen to you. --Your Trusty Server");
    else
        //Send the message to everyone but the person who said it
        foreach ( $Server->wsClients as $id => $client )
            if ( $id != $clientID )
                $Server->wsSend($id, "Visitor $clientID ($ip) said "$message"");
}

// when a client connects
function wsOnOpen($clientID)
{
    global $Server;
    $ip = long2ip( $Server->wsClients[$clientID][6] );

    $Server->log( "$ip ($clientID) has connected." );

    //Send a join notice to everyone but the person who joined
    foreach ( $Server->wsClients as $id => $client )
        if ( $id != $clientID )
            $Server->wsSend($id, "Visitor $clientID ($ip) has joined the room.");
}

// when a client closes or lost connection
function wsOnClose($clientID, $status) {
    global $Server;
    $ip = long2ip( $Server->wsClients[$clientID][6] );

    $Server->log( "$ip ($clientID) has disconnected." );

    //Send a user left notice to everyone in the room
    foreach ( $Server->wsClients as $id => $client )
        $Server->wsSend($id, "Visitor $clientID ($ip) has left the room.");
}

// start the server
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
// for other computers to connect, you will probably need to change this to your LAN IP or external IP,
// alternatively use: gethostbyaddr(gethostbyname($_SERVER['SERVER_NAME']))
$Server->wsStartServer('192.168.1.12', 9300);


?>

index.html on web/chatLogPat

    <!doctype html>
<html>
<head>
    <meta charset='UTF-8' />
    <style>
        input, textarea {border:1px solid #CCC;margin:0px;padding:0px}

        #body {max-width:800px;margin:auto}
        #log {width:100%;height:400px}
        #message {width:100%;line-height:20px}
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="fancywebsocket.js"></script>
    <script>
        var Server;

        function log( text ) {
            $log = $('#log');
            //Add text to log
            $log.append(($log.val()?"n":'')+text);
            //Autoscroll
            $log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
        }

        function send( text ) {
            Server.send( 'message', text );
        }

        $(document).ready(function() {
            log('Connecting...');
            Server = new FancyWebSocket('wss://serveurarchaux.synology.me:9300');

            $('#message').keypress(function(e) {
                if ( e.keyCode == 13 && this.value ) {
                    log( 'You: ' + this.value );
                    send( this.value );

                    $(this).val('');
                }
            });

            //Let the user know we're connected
            Server.bind('open', function() {
                log( "Connected." );
            });

            //OH NOES! Disconnection occurred.
            Server.bind('close', function( data ) {
                log( "Disconnected." );
            });

            //Log any messages sent from server
            Server.bind('message', function( payload ) {
                log( payload );
            });

            Server.connect();
        });
    </script>
</head>

<body>
    <div id='body'>
        <textarea id='log' name='log' readonly='readonly'></textarea><br/>
        <input type='text' id='message' name='message' />
    </div>
</body>

</html>

Oracle cloud linux Centos8 — when executing: yum install php-mysql get error! how to solve

yum install php-mysql
Failed loading plugin “osmsplugin”: No module named ‘librepo’
Last metadata expiration check: 0:01:56 ago on Mon 10 Jan 2022 10:31:23 AM GMT.
Error:
Problem: conflicting requests

  • package php55w-mysql-5.5.38-1.w7.x86_64 requires php55w-pdo(x86-64), but none of the providers can be installed
  • package php56w-mysql-5.6.40-1.w7.x86_64 requires php56w-pdo(x86-64), but none of the providers can be installed
  • package php70w-mysql-7.0.33-1.w7.x86_64 requires php70w-pdo(x86-64), but none of the providers can be installed
  • package php71w-mysql-7.1.26-1.w7.x86_64 requires php71w-pdo(x86-64), but none of the providers can be installed
  • package php71w-mysql-7.1.27-1.w7.x86_64 requires php71w-pdo(x86-64), but none of the providers can be installed
  • package php71w-mysql-7.1.28-1.w7.x86_64 requires php71w-pdo(x86-64), but none of the providers can be installed
  • package php71w-mysql-7.1.29-1.w7.x86_64 requires php71w-pdo(x86-64), but none of the providers can be installed
  • package php71w-mysql-7.1.30-1.w7.x86_64 requires php71w-pdo(x86-64), but none of the providers can be installed
  • package php71w-mysql-7.1.31-1.w7.x86_64 requires php71w-pdo(x86-64), but none of the providers can be installed
  • package php71w-mysql-7.1.32-1.w7.x86_64 requires php71w-pdo(x86-64), but none of the providers can be installed
  • package php71w-mysql-7.1.33-1.w7.x86_64 requires php71w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.14-1.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.16-1.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.17-1.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.19-1.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.21-1.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.22-1.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.24-1.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.27-1.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.31-2.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.32-1.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php72w-mysql-7.2.34-1.w7.x86_64 requires php72w-pdo(x86-64), but none of the providers can be installed
  • package php55w-pdo-5.5.38-1.w7.x86_64 is filtered out by modular filtering
  • package php56w-pdo-5.6.40-1.w7.x86_64 is filtered out by modular filtering
  • package php70w-pdo-7.0.33-1.w7.x86_64 is filtered out by modular filtering
  • package php71w-pdo-7.1.26-1.w7.x86_64 is filtered out by modular filtering
  • package php71w-pdo-7.1.27-1.w7.x86_64 is filtered out by modular filtering
  • package php71w-pdo-7.1.28-1.w7.x86_64 is filtered out by modular filtering
  • package php71w-pdo-7.1.29-1.w7.x86_64 is filtered out by modular filtering
  • package php71w-pdo-7.1.30-1.w7.x86_64 is filtered out by modular filtering
  • package php71w-pdo-7.1.31-1.w7.x86_64 is filtered out by modular filtering
  • package php71w-pdo-7.1.32-1.w7.x86_64 is filtered out by modular filtering
  • package php71w-pdo-7.1.33-1.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.14-1.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.16-1.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.17-1.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.19-1.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.21-1.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.22-1.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.24-1.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.27-1.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.31-2.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.32-1.w7.x86_64 is filtered out by modular filtering
  • package php72w-pdo-7.2.34-1.w7.x86_64 is filtered out by modular filtering
    (try to add ‘–skip-broken’ to skip uninstallable packages or ‘–nobest’ to use not only best candidate packages)

Why Laravel cannot subscribe to PrivateChannel over Laravel Echo?

In my Laravel 8 project, I use laravel-websockets to send messages over websocket, laravel echo to receive messages. If I use Channel class for broadcasting, everything works great whereas I use PrivateChannel, socket connection can be established, yet no subscription is done. Hence I cannot send/receive message over websocket, but ping/pong messages can be seen on inspector of browser.

Most of stackoverflow questions were replied according to static named channels, but I have dynamic named channels that belongs to each users.

You can see my related code blocks below.

<app.php>

AppProvidersBroadcastServiceProvider::class //ADDED-to providers

<BroadcastServiceProvider.php>

Broadcast::routes(['middleware' => 'auth:sanctum']); //ADDED-auth by sanctum

<channels.php>

Broadcast::channel('task-emmiter{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});
//ADDED

<MessageManager.php>

public function broadcastOn()
{
    //Channel works, PrivateChannel not
    return new PrivateChannel('task-emmiter'.$this->receiver); 
}

<websocket.js>

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'ABCDEFG',
    wsHost: window.location.hostname,
    wsPort: 6001,
    forceTLS: false,
    disableStats: true,
}).private('task-emmiter' + mainUser.id)
    .listen('MessageManager', (e) => {
        console.log(e.message);
    });

getting realtime directs using mgp-instagram private api

we have a simple sample code as realtime client in mgp-instagram private api into examples directory which named realtimeClient.php

after running this file from command line that wait receiving on some rtc commands such as

live-started, thread-created and after that when i get new thread from anyone or when our threads updated with new messages, i don’t get any result and output in terminal

can anybody help me how can i get this actions? receiving new messages or updating threads

<?php
set_time_limit(0);
date_default_timezone_set('UTC');

require __DIR__.'/../vendor/autoload.php';

/////// CONFIG ///////
$username = 'xxxxxx';
$password = 'xxxxxx';
$debug = true;
$truncatedDebug = false;
//////////////////////

$ig = new InstagramAPIInstagram($debug, $truncatedDebug);

try {
    $ig->login($username, $password);
} catch (Exception $e) {
    echo 'Something went wrong: '.$e->getMessage()."n";
    exit(0);
}

$loop = ReactEventLoopFactory::create();
if ($debug) {
    $logger = new MonologLogger('rtc');
    $logger->pushHandler(new MonologHandlerStreamHandler('php://stdout', MonologLogger::INFO));
} else {
    $logger = null;
}
$rtc = new InstagramAPIRealtime($ig, $loop, $logger);
$rtc->on('live-started', function (InstagramAPIRealtimePayloadLiveBroadcast $live) {
    printf('[RTC] Live broadcast %s has been started%s', $live->getBroadcastId(), PHP_EOL);
});
$rtc->on('live-stopped', function (InstagramAPIRealtimePayloadLiveBroadcast $live) {
    printf('[RTC] Live broadcast %s has been stopped%s', $live->getBroadcastId(), PHP_EOL);
});
$rtc->on('direct-story-created', function (InstagramAPIResponseModelDirectThread $thread) {
    printf('[RTC] Story %s has been created%s', $thread->getThreadId(), PHP_EOL);
});
$rtc->on('direct-story-updated', function ($threadId, $threadItemId, InstagramAPIResponseModelDirectThreadItem $threadItem) {
    printf('[RTC] Item %s has been created in story %s%s', $threadItemId, $threadId, PHP_EOL);
});
$rtc->on('direct-story-screenshot', function ($threadId, InstagramAPIRealtimePayloadStoryScreenshot $screenshot) {
    printf('[RTC] %s has taken screenshot of story %s%s', $screenshot->getActionUserDict()->getUsername(), $threadId, PHP_EOL);
});
$rtc->on('direct-story-action', function ($threadId, InstagramAPIResponseModelActionBadge $storyAction) {
    printf('[RTC] Story in thread %s has badge %s now%s', $threadId, $storyAction->getActionType(), PHP_EOL);
});
$rtc->on('thread-created', function ($threadId, InstagramAPIResponseModelDirectThread $thread) {
    printf('[RTC] Thread %s has been created%s', $threadId, PHP_EOL);
});
$rtc->on('thread-updated', function ($threadId, InstagramAPIResponseModelDirectThread $thread) {
    printf('[RTC] Thread %s has been updated%s', $threadId, PHP_EOL);
});
$rtc->on('thread-notify', function ($threadId, $threadItemId, InstagramAPIRealtimePayloadThreadAction $notify) {
    printf('[RTC] Thread %s has notification from %s%s', $threadId, $notify->getUserId(), PHP_EOL);
});
$rtc->on('thread-seen', function ($threadId, $userId, InstagramAPIResponseModelDirectThreadLastSeenAt $seenAt) {
    printf('[RTC] Thread %s has been checked by %s%s', $threadId, $userId, PHP_EOL);
});
$rtc->on('thread-activity', function ($threadId, InstagramAPIRealtimePayloadThreadActivity $activity) {
    printf('[RTC] Thread %s has some activity made by %s%s', $threadId, $activity->getSenderId(), PHP_EOL);
});
$rtc->on('thread-item-created', function ($threadId, $threadItemId, InstagramAPIResponseModelDirectThreadItem $threadItem) {
    printf('[RTC] Item %s has been created in thread %s%s', $threadItemId, $threadId, PHP_EOL);
});
$rtc->on('thread-item-updated', function ($threadId, $threadItemId, InstagramAPIResponseModelDirectThreadItem $threadItem) {
    printf('[RTC] Item %s has been updated in thread %s%s', $threadItemId, $threadId, PHP_EOL);
});
$rtc->on('thread-item-removed', function ($threadId, $threadItemId) {
    printf('[RTC] Item %s has been removed from thread %s%s', $threadItemId, $threadId, PHP_EOL);
});

//...

$rtc->start();

$loop->run();

Twig – Different Variables/Functions for one twig.html

Since 3 weeks i try to learn php with the symfony framework.
I want to build an application with which i can track my expanses.

I made good progress but since 2 days i have a little logic problem so maybe someone can help me here.

I want to make a dashboard.(the main side of the project) There the user can monitor the expenditures.
This works. Now i want also a form at the dashboard, so the user can add new expenditures. I already implement a form but with a extra route. So in my ExpenditureController i have the functions dashboard and the function addExpenditure which generate different twig.html templates.

So the user can monitor his expenditures with …budgetapp/expenditure/dashboard
and he can add new Expenditure with …budgetapp/expenditure/addexpenditure

My Dashboard-Function

    #[Route('/dashboard/', name: 'dashboard')]
public function dashboard(ExpenditureRepository $ar)
   {
    $user = $this->getUser();
    $expenditures = $ar-> findexpendituresOfUser($user);

    return $this->render('expenditure/dashboard.html.twig', [
    'expenditures' => $expenditures,
       ]);
}

The expenditure/dashboard.html.twig shows the Expentiures of the current user in a table

My addExpenditure-Function
public function addExpenditure (ManagerRegistry $doctrine, Request $request){

    $em = $doctrine->getManager();
    $expenditure = new Expenditure();
    $form = $this->createForm(ExpenditureType::class, $Expenditure);
    $form->handleRequest($request);

    if($form->isSubmitted()){
    $em->persist($expenditure);
    $em->flush();
    }

    return $this->render('expenditure/addexpenditure.html.twig', [
        'addexpenditureForm' => $form->createView()
    ]);
}

The expenditure/addexpenditure.html.twig looks like this:

{% block body %}
<div class="container">
{{form(eintragenForm)}}
</div>
{% endblock %}

My problem /mistake in thinking:
How can i implement the form to the dashboard? So of course i can take the code from the addexpenditure function and put it 1:1 in the dashboard-funciton. but i dont think this is the right way? I also tried to including template fragments with the offical Embedding Controllers Documentation of Symfony, but this also dont work.
So someone can help me with a suggestion how you would handle this in your project?

Best regards
Markus