OrderBy Laravel Eloquent Relationship

I would like to order listing_data based on listing_packages.order . Here is the query

ListingData::with(['listing_package'])->orderBy('listing_package.order','desc')->paginate(24);

I would like to order based on listing_package.order “DESCENDING”

However, it returns

SQLSTATE[42S22]: Column not found: 1054 Unknown column
‘listing_package.order’ in ‘order clause’

Here is the model ListingData.php

public function listing_package(): BelongsTo
{
    return $this->belongsTo(ListingPackage::class);
}

Here is the model for ListingPackage.php

public function listing_data(): HasMany {
    return $this->hasMany(ListingData::class);
}

Edit:

I also try this one

    $relations = [
        'district',
        'regency',
        'province',
        'category',
        'type',
        'rentType',
        'listing_package' => function ($q){
            $q->orderBy('order','DESC');
        },
    ];
    $listings = ListingData::with($relations)
    ->latest()
        ->paginate(24);

But the data is not sorted

Am I missing something here?

PHP testing all post values for string

We are using stristr to test if someone included a link in the question textarea on a form. And it works fairly well to keep spam at bay. But newer attempts by miscreants have started putting the spam links in other inputs such as name, address, city, etc.

Our current code:

// check if question box has links and die if so 
$has_link = stristr($_POST['question'], 'http://') ?: stristr($_POST['question'], 'https://');
if($has_link){
  die('Your submission was blocked. Do not submit links to websites.');
}

Is there a way to write this so that it tests any and all POST variables without having to write out each one individually ie, $_POST['question'], $_POST['name'], $_POST['address']?

Custom Woocommerce Payment Gateway Not Showing on Checkout page

I am in the process of creating a plugin to integrate a custom WooCommerce payment gateway. Although I have successfully activated it in the admin panel but the payment option does not yet appear on the checkout page.

WooCommerce version: 8.4.0

WordPress version: 6.4.2

Here is the complete code of my plugin

if (!defined("ABSPATH")) {
    exit(); // Exit if accessed directly.
}

// Hook to plugins_loaded to ensure WooCommerce is loaded
add_action("plugins_loaded", "init_woocommerce_to_stripe", 0);

function init_woocommerce_to_stripe()
{
    if (!class_exists("WC_Payment_Gateway")) {
        return;
    }

    // Define the custom payment gateway class
    class WC_Gateway_WooCommerce_To_Stripe extends WC_Payment_Gateway
    {
        // Declare properties
        public $redirect_url;

        public function __construct()
        {
            // Basic setup for the gateway
            $this->id = "woocommerce_to_stripe";
            $this->has_fields = false;
            $this->icon = "";
            $this->method_title = "WooCommerce to Stripe";
            $this->method_description =
                "Redirects users to a custom URL with order ID and total amount for Stripe payments.";
            $this->supports = [];

            // Initialize settings
            $this->init_form_fields();
            $this->init_settings();

            // Get settings values
            $this->title = $this->get_option("title");
            $this->description = $this->get_option("description");
            $this->enabled = $this->get_option("enabled");

            // Use the constructor to set dynamic properties
            $this->redirect_url = $this->get_option(
                "redirect_url",
                "https://www.example.com/"
            ); // Default redirect URL

            // Save settings on WooCommerce admin options update
            add_action(
                "woocommerce_update_options_payment_gateways_" . $this->id,
                [$this, "process_admin_options"]
            );
        }

        // Define form fields for WooCommerce settings
        public function init_form_fields()
        {
            $this->form_fields = [
                "enabled" => [
                    "title" => "Enable/Disable",
                    "type" => "checkbox",
                    "label" => "Enable WooCommerce to Stripe",
                    "default" => "yes",
                ],
                "title" => [
                    "title" => "Title",
                    "type" => "text",
                    "description" =>
                        "This controls the title which the user sees during checkout.",
                    "default" => "WooCommerce to Stripe",
                    "desc_tip" => true,
                ],
                "description" => [
                    "title" => "Description",
                    "type" => "textarea",
                    "description" =>
                        "This controls the description which the user sees during checkout.",
                    "default" =>
                        "Redirects users to a custom URL with order ID and total amount for Stripe payments.",
                ],
                "redirect_url" => [
                    "title" => "Redirect URL",
                    "type" => "text",
                    "description" =>
                        "Enter the custom URL where users will be redirected with order ID and total amount.",
                    "default" => "https://www.example.com/",
                ],
            ];
        }

        // Process payment and redirect to the custom URL
        public function process_payment($order_id)
        {
            $order = wc_get_order($order_id);

            // Redirect URL with order ID and total amount as query parameters
            $redirect_url =
                $this->redirect_url .
                "?order_id=" .
                $order_id .
                "&total_amount=" .
                $order->get_total();

            return [
                "result" => "success",
                "redirect" => $redirect_url,
            ];
        }
    }

    // Register the custom payment gateway class
    function add_woocommerce_to_stripe_gateway($gateways)
    {
        $gateways[] = "WC_Gateway_WooCommerce_To_Stripe";

        return $gateways;
    }

    // Filter to add the custom payment gateway class
    add_filter(
        "woocommerce_payment_gateways",
        "add_woocommerce_to_stripe_gateway",
        999
    );
}

Dividing results table in PHP into collapsible sub-tables

I am revising the question I asked before that was not clear at all.
I am very much new to PHP programming.
I have a table in postgres:

| gene_name | description|
| gene1     | kuku       | 
| gene1     | blabla     |
| gene2     | tralala    |

I have a search form with an option to search with the gene name or the description column and I am fetching the result and presenting it in html with the following code:


    $search_input = test_input($_GET["search_keywords"]);
     $searched_by = test_input($_GET["search_by"]);
     $query = "SELECT * FROM gene WHERE lower($searched_by) SIMILAR TO       '%".pg_escape_string(search_input)."%'

    $res = pg_query($query) or die('Query failed: ' . pg_last_error());
    
    if ($res) {
    // Printing results in HTML
    echo "<table id="tblAnnotations" class="table annot_table">n<thead><tr><th>Gene</th>    <th>Term</th></tr>";
  
    while ($line = pg_fetch_array($res, null, PGSQL_ASSOC)) {
      $found_gene = $line["gene_name"];
      $found_desc = $line["description"];
            
    echo "<tr><td>$found_gene</a></td><td><td>$found_desc</td></tr>n";
    }
    echo "</tbody>n</table>n";
    }
    else {
    echo "<p>No results found.</p>n";
    }
   
    pg_free_result($res);

I want to have separate sub-tables for each gene with the header of the gene name, and I just cannot get how to do it properly.

The output i want is:

| gene_name | description|
gene1 
| gene1     | kuku       | 
| gene1     | blabla     |
gene2
| gene2     | tralala    |

I tried adding a uniquegene variable and adding a loop, that will put a header above each sub-table, but it doesn’t work at all, i get an empty result, so I clearly do smth very basic wrong. Will be grateful for your help!

$uniqueGenes[] = array_unique($line["gene_name"]);
     foreach ($uniqueGenes as $uniqueGene) {
     echo "<h4>$uniqueGene</h4>";
     }   

Disable Laravel debugger

I have a Laravel application that was not developed by me. There is some weird bar at the bottom of each page, it is some type of Laravel debugger tool.

I believe it is stored in storage/debugger. Is there a safe way I can go about checking to see if this is actually it and if so can I delete this type of tool without it affecting the application? Does anybody know what this thing is if so any advice on how to remove this safely would be greatly appreciated.

Thank you.

I had searched online and I had seen most of solution are related to.env file. But I am unable to find.env file in code.

How to find both IPv6 and IPv4 with PHP?

When I look up my ip address on a website, it offers both my IPv6 and IPv4 address. When I use a PHP-script it only return the IPv6 address (both $_SERVER[‘REMOTE_ADDR’] and getenv(‘REMOTE_ADDR’)).

How do these websites get my IPv4 address?

I have looked into all the $_SERVER variables but cannot find it.

Stripe pass client secret to js from PHP

I have a code that supposed to retrieve client secret and pass it to js but it doens’t work as I get error 500. I have created a function called retrieve_client_secret() that’s supposed to retrieve it but seems it’s not the right way.
Maybe I have to use AJAX to fetch the client secret before processing to payment procedure?

<?php
/**
 * Plugin Name: Stripe-PHP-integration
 * Description: PHP API Integration For WordPress
 * Author: Null
 * Version: 1.0
**/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

require_once 'stripe/init.php';

use StripeStripe;

add_action('init', function() {

    Stripe::setApiKey('sk_test_');
    Stripe::setClientId('pk_test_');

});

header('Content-Type: application/json');



add_action('plugins_loaded', 'init_custom_gateway_class');
function init_custom_gateway_class(){

    class WC_Gateway_Custom extends WC_Payment_Gateway {


        /**
         * Constructor for the gateway.
         */
        public function __construct() {

            $this->id                 = 'Stripe-Payment';
            $this->icon               = apply_filters('woocommerce_custom_gateway_icon', '');
            $this->has_fields         = true;
            $this->method_title       = __( 'Stripe PHP API Integration For WooCommerce', $this->domain );
            $this->method_description = __( 'Allows payments using Stripe PHP API', $this->domain );

            // Load the settings.
            $this->init_form_fields();
            $this->init_settings();


            // Define user set variables
            $this->title        = $this->get_option( 'title' );
            $this->description  = $this->get_option( 'description' );
            $this->instructions = $this->get_option( 'instructions', $this->description );
            $this->order_status = $this->get_option( 'order_status', 'pending' );
            

            // Actions
            add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
            add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'thankyou_page' ) );

            // Customer Emails
            add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
            add_action('woocommerce_payment_fields', array($this, 'payment_fields'));
            add_action('wp_enqueue_scripts', array($this, 'enqueue_styles'));
            add_action('wp_footer', array($this, 'include_stripe_js'));
            
            add_action('init', array($this, 'retrieve_client_secret'));
            
            



        }
        
        
        public function enqueue_styles() {
            wp_enqueue_style('stripe-custom-styles', 'https://getvagu.com/wp-content/plugins/woocommerce-gateway-stripe/assets/css/stripe-styles.css?ver=7.7.0');
        }
        
        public function include_stripe_js() {
                ?>
                <script src="https://js.stripe.com/v3/"></script>
                <script>
                    const stripe = Stripe('pk_test_');
                    let elements;
                    
                    const options = {
                    mode: 'payment',
                    amount: 1099,
                    currency: 'usd',
                    appearance: {/*...*/},
                    clientSecret: '<?php echo retrieve_client_secret() ?>'
                    };
                    
                    
                    initialize();
                    
                    document.querySelector("#stripe_form_checkout").addEventListener("submit", handleSubmit); 

                    
                    function initialize() {
                        elements = stripe.elements(options);
                    
                        const paymentElement = elements.create('payment', {
                            fields: {
                                billingDetails: {
                                    address: {
                                        country: 'never'
                                    }
                                }
                            }
                        });
                    
                        paymentElement.mount('#stripe_payment');
                    }
                    
                    
                    
                    async function handleSubmit(e) {
                      e.preventDefault();
                    
                      const { setupIntent, error } = await stripe.confirmSetup({
                        elements,
                        confirmParams: {
                          return_url: "https://getvagu.com/checkout",
                        },
                        redirect: 'if_required'
                      });
                    
                     
                      if(error) {

                      if (error.type === "card_error" || error.type === "validation_error") {
                        showMessage(error.message);
                      } else {
                        showMessage("An unexpected error occurred.");
                      }
                      
                      } else {
                          console.log(setupIntent)
                      }
                      
                      
                    
                    }
                                        
                    

                    
                                                                                
                                                            
                                        
                    
                    
                    
                    
                    
                </script>
                <?php
        }
        
                

        /**
         * Initialise Gateway Settings Form Fields.
         */
        public function init_form_fields() {

            $this->form_fields = array(
                'enabled' => array(
                    'title'   => __( 'Enable/Disable', $this->domain ),
                    'type'    => 'checkbox',
                    'label'   => __( 'Enable Custom Payment', $this->domain ),
                    'default' => 'yes'
                ),
                'title' => array(
                    'title'       => __( 'Title', $this->domain ),
                    'type'        => 'text',
                    'description' => __( 'This controls the title which the user sees during checkout.', $this->domain ),
                    'default'     => __( 'Stripe PHP API', $this->domain ),
                    'desc_tip'    => true,
                ),
                'order_status' => array(
                    'title'       => __( 'Order Status', $this->domain ),
                    'type'        => 'select',
                    'class'       => 'wc-enhanced-select',
                    'description' => __( 'Choose whether status you wish after checkout.', $this->domain ),
                    'default'     => 'wc-completed',
                    'desc_tip'    => true,
                    'options'     => wc_get_order_statuses()
                ),
                'description' => array(
                    'title'       => __( 'Description', $this->domain ),
                    'type'        => 'textarea',
                    'description' => __( 'Payment method description that the customer will see on your checkout.', $this->domain ),
                    'default'     => __('Payment Information', $this->domain),
                    'desc_tip'    => true,
                ),
                'instructions' => array(
                    'title'       => __( 'Instructions', $this->domain ),
                    'type'        => 'textarea',
                    'description' => __( 'Instructions that will be added to the thank you page and emails.', $this->domain ),
                    'default'     => '',
                    'desc_tip'    => true,
                ),
            );
        }
        
        
        

        /**
         * Output for the order received page.
         */
        public function thankyou_page() {
            if ( $this->instructions )
                echo wpautop( wptexturize( $this->instructions ) );
        }

        /**
         * Add content to the WC emails.
         *
         * @access public
         * @param WC_Order $order
         * @param bool $sent_to_admin
         * @param bool $plain_text
         */
        public function email_instructions( $order, $sent_to_admin, $plain_text = false ) {
            if ( $this->instructions && ! $sent_to_admin && $order->payment_method && $order->has_status( 'on-hold' ) ) {
                echo wpautop( wptexturize( $this->instructions ) ) . PHP_EOL;
            }
        }
        
        
        

        /**
         * Renders the Stripe elements form.
         *
         */
        public function payment_fields(){
            ?>
                <div id="stripe_payment_form"></div>
            <?php
        }
        
        
    
        
        
        
        public function retrieve_client_secret(){
            $payment_intent = StripePaymentIntent::create([
                'amount' => $order->get_total() * 100,
                'currency' => strtolower(get_woocommerce_currency()),
            ]);
            
            $clientSecret = $payment_intent->clientSecret;
            return $clientSecret;
        }
            
    
            
        

        /**
         * Process the payment and return the result.
         *
         * @param int $order_id
         * @return array
         */
        public function process_payment( $order_id ) {

            $order = wc_get_order( $order_id );
            
            
            

            // Set order status
            $order->update_status('pending', __('Waiting for payment confirmation', $this->domain));

            // or call the Payment complete
            // $order->payment_complete();


            // Remove cart
            WC()->cart->empty_cart();

            // Return thankyou redirect
            return array(
                'result' => 'success',
                'redirect'  => $this->get_return_url($order),
            );
        }
    }
}

add_filter( 'woocommerce_payment_gateways', 'Stripe_PHP_API_Woocommerce_Integration' );
function Stripe_PHP_API_Woocommerce_Integration( $methods ) {
    $methods[] = 'WC_Gateway_Custom'; 
    return $methods;
}



?>

How to append disable_funtions in .user.ini

I am using Apache 2 and php-fpm(7.2.24). I am currently managing multiple virtualHosts, so I am using .user.ini to manage them. Now, I would like to add a “disable_functions” to a “user. ini” file (note:not lifting, but adding some restrictions), but I found it useless, I failed. This seems to be inconsistent with what is said on this page https://www.php.net/manual/en/install.fpm.configuration.php:“PHP settings passed with php_value or php_flag will overwrite their previous value. Please note that defining disable_functions or disable_classes will not overwrite previously defined php.ini values, but will append the new value instead.”

What should I do

When I generate a submenu under an admin menu, it inadvertently turns the main menu into a submenu too. How can I prevent this from happening?

main menu and submenu
As the title suggests, I wish to avoid the main menu from becoming a submenu.

When I generate a submenu under an admin menu, it inadvertently turns the main menu into a submenu too. How can I prevent this from happening? Additionally, when clicking on the main menu, I want it to navigate to the first submenu rather than a separate main menu page. Here is the code.

// Hook to add the custom menu
add_action('admin_menu', 'custom_admin_menu');

// Function to create the custom menu
function custom_admin_menu() {
    // Add top-level menu
    add_menu_page(
        'Custom Menu',          // Page title
        'Custom Menu',          // Menu title
        'manage_options',       // Capability
        'custom-menu',          // Menu slug
        'custom_menu_display', // Callback function to display the menu page
        'dashicons-chart-bar'   // Icon URL or Dashicon class
    );

    // Add submenu
    add_submenu_page(
        'custom-menu',          // Parent menu slug
        'Custom Submenu',       // Page title
        'Custom Submenu',       // Menu title
        'manage_options',       // Capability
        'custom-submenu',       // Menu slug
        'custom_submenu_display' // Callback function to display the submenu page
    );

    // Add another submenu
    add_submenu_page(
        'custom-menu',          // Parent menu slug
        'Another Submenu',       // Page title
        'Another Submenu',       // Menu title
        'manage_options',       // Capability
        'another-submenu',       // Menu slug
        'another_submenu_display' // Callback function to display the submenu page
    );
}

// Function to display the menu page
function custom_menu_display() {
    ?>
    <div class="wrap">
        <h2>Custom Menu</h2>
        <p>This is my custom menu page content.</p>
    </div>
    <?php
}

// Function to display the custom submenu page
function custom_submenu_display() {
    ?>
    <div class="wrap">
        <h2>Custom Submenu</h2>
        <p>This is my custom submenu page content.</p>
    </div>
    <?php
}

// Function to display the another submenu page
function another_submenu_display() {
    ?>
    <div class="wrap">
        <h2>Another Submenu</h2>
        <p>This is my another submenu page content.</p>
    </div>
    <?php
}

How can I Dockerize my Symfony Application?

Recently I started developing a website using symfony. My goal is symply to learn, and as such I am using a variety of different depencies and quite a few node modules.

Now I have already looked into a lot of documentation about docker and symfony, however nothing I can find has really helped me.

The largest frameworks/techs I am using are symfony-7, webpack (encore), twig, doctrine and bootstrap-5.3 along with as mentioned quite a few other composer-“modules” and node-modules.

In my project I have a docker-compose file.

Any help or pointers towards the right direction are massively appreciated!

Invalid Token > Firebase JWT auth decode verification ID

I can’t get to get the validation of an Google Firebase Authentication ID to work. It returns me the exception: Fatal error: Uncaught Exception: Invalid token signature!

I’ve made a login using Firebase Authentication (javascript) and now i want to pass on the ID to a server (PHP) and validate the ID within the script (to make sure someone is loggedin)
For this I need to use the JWT library (Which seems to be working).

May be i’m using the wrong key / not looping properly through it, but i ran out of options to try… The code contains an example token i try to validate.

<?php

require_once("Firebase/JWT/Key.php");
require_once("Firebase/JWT/JWTExceptionWithPayloadInterface.php");
require_once("Firebase/JWT/ExpiredException.php");
require_once("Firebase/JWT/SignatureInvalidException.php");
require_once("Firebase/JWT/BeforeValidException.php");
require_once("Firebase/JWT/JWT.php");


use FirebaseJWTKey;
use FirebaseJWTJWTExceptionWithPayloadInterface;
use FirebaseJWTExpiredException;
use FirebaseJWTSignatureInvalidException;
use FirebaseJWTBeforeValidException;
use FirebaseJWTJWT;


$publicKeyURL = 'https://www.googleapis.com/robot/v1/metadata/x509/[email protected]';
$key = json_decode(file_get_contents($publicKeyURL), true);

$token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjUyNmM2YTg0YWMwNjcwMDVjZTM0Y2VmZjliM2EyZTA4ZTBkZDliY2MiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoiUm9sZiBCcm9lciIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9zd2lwZS01YWQ5NCIsImF1ZCI6InN3aXBlLTVhZDk0IiwiYXV0aF90aW1lIjoxNzA0NDQ4NjYyLCJ1c2VyX2lkIjoicDNIbnBMOVo5UWVqOXdjajBtY0tITGxuYmh6MSIsInN1YiI6InAzSG5wTDlaOVFlajl3Y2owbWNLSExsbmJoejEiLCJpYXQiOjE3MDQ0NDk5MDAsImV4cCI6MTcwNDQ1MzUwMCwiZW1haWwiOiJyb2xmYnJvZXJAZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJmaXJlYmFzZSI6eyJpZGVudGl0aWVzIjp7ImVtYWlsIjpbInJvbGZicm9lckBnbWFpbC5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.CrHpVyacsFbqMwrcl1vgWCi4x3M3zlyplyG-amplQuilwBHRAxh4V0GKJh9cVfcPd3w_iw40a_MPmhN0aBwkx0Pg4XwVjnArr0-f8Kwj4OosGo3J0d28LGpVjbk0wlyw9EwG4MGTTbXhvzUkHKEatPpTUX9Ly_8MEvs1msojXRG2bWIFHEfgQuAiN5aWW2-uYpRbAuZ2H02OuYNTKeH26Ok6s6lzf7Gcpy_kAE5WO_p7PRDTiWg2BZAjjuCvfEtAmELPzia9SEr3oLWJfdiiet4G28KJA1jTJb5qvfQzPvcRTWzvJrQevYdQbROP0POF-Jsl3jA979JUq1CwBQWzmA";

validate($token, $key);

function validate($jwt_token, $keyData) {
    $algorithm = array('RS256');

    try {
        // Select a specific key from the array
        $selectedKey = current($keyData);

        // Create an instance of FirebaseJWTKey
        $key = new FirebaseJWTKey($selectedKey, 'RS256');

        // Convert $algorithm to an object as the third argument
        $algorithmObject = (object) $algorithm;

        return JWT::decode($jwt_token, $key, $algorithmObject);
    } catch (ExpiredException $e) {
        throw new Exception('Token expired!');
    } catch (SignatureInvalidException $e) {
        throw new Exception('Invalid token signature!');
    } catch (BeforeValidException $e) {
        throw new Exception('Token not valid yet!');
    } catch (Exception $e) {
        throw new Exception('Invalid token!');
    }
}
?>

I’ve tried to use the API key, the project ID instead of the current public keys, but those don’t seem to be correct either.

Creating individual sorting at runtime with shopware 6

I am trying to create a sorting without using the Database Migration. I tried doing it as described in the documentation but I get the error that the “custom-sorting” couldn’t be found. I tried using the AbstractListingProcessor instead the subscriber but it didn’t work as well.
Here is a snippet of my code:

  class CustomSortingProcessor extends AbstractListingProcessor
 {
      public function getDecorated() : AbstractListingProcessor
      {
          throw new DecorationPatternException(self::class);
      }

public function prepare(Request $request, Criteria $criteria, SalesChannelContext 
    $context): void

    /** @var ProductSortingCollection $availableSortings */
    $availableSorting = $criteria->getExtension('sortings') ?? new 
     ProductSortingCollection();

    $customSortingProcessorEntity = new ProductSortingEntity();
    $customSortingProcessorEntity ->setId(Uuid::randomHex());
    $customSortingProcessorEntity ->setActive(true);
    $customSortingProcessorEntity ->setTranslated(['label' => 'Custom Sorting']);
    $customSortingProcessorEntity ->setKey('custom-sorting-by');
    $customSortingProcessorEntity ->setPriority(5);
    $customSortingProcessorEntity ->setFields([
        [
            'field' => 'deepLearning.sold',
            'order' => 'desc',
            'priority' => 1,
            'naturalSorting' => 0,
        ],
    ]);

    $availableSorting->add($customSortingProcessorEntity);

    $criteria->addExtension('sortings', $availableSorting);
        }
      }

Woocommerce stripe Credit card input field appear then suddenly disappears after page is loaded

When page is not fully loaded yet the stripe card input element appears, but when page is fully loaded it suddenly disappears.

Sometimes I get this error message – ‘controller-cc848a9ad…2497a003323d67.js:1 [Stripe.js] The selector you specified (#stripe-card-element) applies to 2 DOM elements that are currently on the page. The Stripe Element will be mounted to the first one.’

<?php
/**
 * Plugin Name: Stripe-PHP-integration
 * Description: PHP API Integration For WordPress
 * Author: Null
 * Version: 1.0
**/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

require_once 'stripe/init.php';

use StripeStripe;

add_action('init', function() {

    Stripe::setApiKey('sk_test_');
    Stripe::setClientId('pk_test_');

});

header('Content-Type: application/json');



add_action('plugins_loaded', 'init_custom_gateway_class');
function init_custom_gateway_class(){

    class WC_Gateway_Custom extends WC_Payment_Gateway {


        /**
         * Constructor for the gateway.
         */
        public function __construct() {

            $this->id                 = 'Stripe PHP Integration';
            $this->icon               = apply_filters('woocommerce_custom_gateway_icon', '');
            $this->has_fields         = false;
            $this->method_title       = __( 'Stripe PHP API Integration For WooCommerce', $this->domain );
            $this->method_description = __( 'Allows payments using Stripe PHP API', $this->domain );

            // Load the settings.
            $this->init_form_fields();
            $this->init_settings();


            // Define user set variables
            $this->title        = $this->get_option( 'title' );
            $this->description  = $this->get_option( 'description' );
            $this->instructions = $this->get_option( 'instructions', $this->description );
            $this->order_status = $this->get_option( 'order_status', 'pending' );
            

            // Actions
            add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
            add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'thankyou_page' ) );

            // Customer Emails
            add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
            add_action('woocommerce_payment_fields', array($this, 'payment_fields'));
            add_action('wp_enqueue_scripts', array($this, 'enqueue_styles'));
            add_action('wp_footer', array($this, 'include_stripe_js'));

            


        }
        
        
        public function enqueue_styles() {
            wp_enqueue_style('stripe-custom-styles', 'https://getvagu.com/wp-content/plugins/woocommerce-gateway-stripe/assets/css/stripe-styles.css?ver=7.7.0');
        }
        
        public function include_stripe_js() {
                ?>
                <script src="https://js.stripe.com/v3/"></script>
                <script>
                    var stripe = Stripe('pk_test_');
                    var elements = stripe.elements();
                    var card = elements.create('card');
                    card.mount('#stripe-card-element');
                    

                </script>
                <?php
        }
        
                

        /**
         * Initialise Gateway Settings Form Fields.
         */
        public function init_form_fields() {

            $this->form_fields = array(
                'enabled' => array(
                    'title'   => __( 'Enable/Disable', $this->domain ),
                    'type'    => 'checkbox',
                    'label'   => __( 'Enable Custom Payment', $this->domain ),
                    'default' => 'yes'
                ),
                'title' => array(
                    'title'       => __( 'Title', $this->domain ),
                    'type'        => 'text',
                    'description' => __( 'This controls the title which the user sees during checkout.', $this->domain ),
                    'default'     => __( 'Stripe PHP API', $this->domain ),
                    'desc_tip'    => true,
                ),
                'order_status' => array(
                    'title'       => __( 'Order Status', $this->domain ),
                    'type'        => 'select',
                    'class'       => 'wc-enhanced-select',
                    'description' => __( 'Choose whether status you wish after checkout.', $this->domain ),
                    'default'     => 'wc-completed',
                    'desc_tip'    => true,
                    'options'     => wc_get_order_statuses()
                ),
                'description' => array(
                    'title'       => __( 'Description', $this->domain ),
                    'type'        => 'textarea',
                    'description' => __( 'Payment method description that the customer will see on your checkout.', $this->domain ),
                    'default'     => __('Payment Information', $this->domain),
                    'desc_tip'    => true,
                ),
                'instructions' => array(
                    'title'       => __( 'Instructions', $this->domain ),
                    'type'        => 'textarea',
                    'description' => __( 'Instructions that will be added to the thank you page and emails.', $this->domain ),
                    'default'     => '',
                    'desc_tip'    => true,
                ),
            );
        }
        
        
        

        /**
         * Output for the order received page.
         */
        public function thankyou_page() {
            if ( $this->instructions )
                echo wpautop( wptexturize( $this->instructions ) );
        }

        /**
         * Add content to the WC emails.
         *
         * @access public
         * @param WC_Order $order
         * @param bool $sent_to_admin
         * @param bool $plain_text
         */
        public function email_instructions( $order, $sent_to_admin, $plain_text = false ) {
            if ( $this->instructions && ! $sent_to_admin && $order->payment_method && $order->has_status( 'on-hold' ) ) {
                echo wpautop( wptexturize( $this->instructions ) ) . PHP_EOL;
            }
        }
        
        
        

        /**
         * Renders the Stripe elements form.
         *
         */
        public function payment_fields() {
            ?>
            <fieldset id="wc-<?php echo esc_attr( $this->id ); ?>-cc-form" class="wc-credit-card-form wc-payment-form" style="background:transparent;">
                <?php do_action( 'woocommerce_credit_card_form_start', $this->id ); ?>
    
                <?php if ( $this->inline_cc_form ) { ?>
                    <label for="card-element">
                        Credit or debit card
                    </label>
    
                    <div id="wc-stripe-elements-field" class="wc-stripe-elements-field">
                    <!-- a Stripe Element will be inserted here. -->
                    </div>
                <?php } else { ?>
                    <div class="form-row form-row-wide mb-3">
                        <label for="stripe-card-element"> Card Number <span class="required">*</span></label>
                        <div class="stripe-card-group">
                            <div id="stripe-card-element" class="wc-stripe-elements-field">
                            <!-- a Stripe Element will be inserted here. -->
                            </div>
    
                            <i class="stripe-credit-card-brand stripe-card-brand" alt="Credit Card"></i>
                        </div>
                    </div>
    
                    <div class="row">
                        <div class="col-8">
                        <label for="stripe-exp-element"> Expiry Date <span class="required">*</span></label>
    
                        <div id="stripe-exp-element" class="wc-stripe-elements-field">
                        <!-- a Stripe Element will be inserted here. -->
                        </div>
                        </div>
    
                        <div class="col-4">
                        <label for="stripe-cvc-element"> CVC <span class="required">*</span></label>
                    <div id="stripe-cvc-element" class="wc-stripe-elements-field">
                    <!-- a Stripe Element will be inserted here. -->
                    </div>
                        </div>
                    </div>
                    
                    <div class="row mt-4">
                        <div class="col-12">
                            <img src="https://getvagu.com/wp-content/uploads/2023/11/secured.png" data-src="https://getvagu.com/wp-content/uploads/2023/11/secured.png" alt="secured" class="img-fluid d-block mx-auto" data-ga-section="7 - Secured Images">
                        </div>
                    </div>
                    
                    
                    <div class="clear"></div>
                <?php } ?>
    
                <!-- Used to display form errors -->
                <div id="stripe-source-errors" class="stripe-source-errors" role="alert"></div>
                <?php do_action( 'woocommerce_credit_card_form_end', $this->id ); ?>
                <div class="clear"></div>
            </fieldset>
            <?php
        }

        /**
         * Process the payment and return the result.
         *
         * @param int $order_id
         * @return array
         */
        public function process_payment( $order_id ) {

            $order = wc_get_order( $order_id );


            $payment_intent = StripePaymentIntent::create([
                'amount' => $order->get_total() * 100,
                'currency' => strtolower(get_woocommerce_currency()),
                'payment_method' => $order->get_payment_method(),
                'confirmation_method' => 'manual',
                'confirm' => true,
                'return_url' => $this->get_return_url($order),
            ]);

            // Set order status
            $order->update_status('pending', __('Waiting for payment confirmation', $this->domain));

            // or call the Payment complete
            // $order->payment_complete();


            // Remove cart
            WC()->cart->empty_cart();

            // Return thankyou redirect
            return array(
                'result' => 'success',
                'redirect' => $payment_intent->client_secret,
            );
        }
    }
}

add_filter( 'woocommerce_payment_gateways', 'Stripe_PHP_API_Woocommerce_Integration' );
function Stripe_PHP_API_Woocommerce_Integration( $methods ) {
    $methods[] = 'WC_Gateway_Custom'; 
    return $methods;
}



?>

Sylius php – how to pass cart to twig template (Sylius Template Events)

The default context provider does not provide a cart object. There’s only channelContext, currencyContext, localeContext and customerContext.

Is it possible to get cart in twig template using Sylius template events?

For example like this:

sylius_ui:
    events:
        sylius.shop.layout.header.content:
            blocks:
                search:
                    enabled: true
                    template: "@App/Layout/Header/_search.html.twig"
                    priority: 10
                    context:
                        cart: how_to_pass_cart? # <-- How to pass cart

And using it in a template, for example:

{# @App/Layout/Header/_search.html.twig #}
{{ cart.itemsTotal }}

Right now, in the standard template, to display the cart, a render of the order controller is used with template substitution.

https://github.com/Sylius/Sylius/blob/a0ad0d1e4c61ed8ec30bbb39e36184cb910736b2/src/Sylius/Bundle/ShopBundle/Resources/views/Layout/Header/_cart.html.twig#L2

<div class="right aligned column">
    {{ render(url('sylius_shop_partial_cart_summary', {'template': '@SyliusShop/Cart/_widget.html.twig'})) }}
</div>

From my point of view this is not a very good solution.
Is there a way to get the cart via context parameter or ContextProvider in twig template?