Reusing Filters Across Multiple Entities in API Platform 3 and Symfony

Title: Reusing Filters Across Multiple Entities in API Platform 3 and Symfony

Hello everyone,

I’m working on a project using API Platform 3 with Symfony, and I’m looking for an effective way to factorize and reuse filters across multiple entities. Here’s a summary of my use case and the challenges I’ve encountered:

  1. Objective: I have common filters (for example, filters on fields like name, createdAt, and updatedAt) that I want to reuse across several entities without duplicating the filter configuration.

  2. Current Configuration: I’ve defined my common filters in a YAML services file. Then, I use the ApiFilter attribute to declare specific filters directly on the entities. However, this forces me to repeat the configuration of common filters for each entity.

  3. Constraint: API Platform’s filter classes are declared as final, preventing me from directly extending them to create “wrapper” classes for the filters. Additionally, the ApiFilter attribute does not accept a service identifier as an argument, limiting my ability to reference the filters defined in the YAML file.

Here’s a snippet of the YAML configuration for the common filters:

services:
  app.api.filter.name_order:
    parent: 'api_platform.doctrine.orm.order_filter'
    arguments: [ { name: ~ } ]
    tags: [ 'api_platform.filter' ]

  app.api.filter.lifecycle_date:
    parent: 'api_platform.doctrine.orm.date_filter'
    arguments: [ { createdAt: ~, updatedAt: ~ } ]
    tags: [ 'api_platform.filter' ]

And an example of using PHP 8 attributes on an entity:

#[ApiResource(
    // Other configurations...
    filters: [
        'hl.name.order_filter',
        'hl.lifecycle.date_filter',
        // Other filters...
    ]
)]
#[ApiFilter(SearchFilter::class, properties: ['name' => 'partial'])]
class SomeEntity {
    // Entity definition...
}

I’ve explored several avenues, like using traits to mark entities or centralizing filter configuration, but none of these solutions seem to offer the flexibility and reusability I’m looking for.

I’m reaching out best practices in this context. Here are some specific points I’d like to clarify:

  • #[ApiFilter('hl.name.order_filter')]: I tried but the ApiFilter is configured to receive a class name only.
  • So I tried to extend default filter like MyFilter extends OrderFilter but they are all final…
  • Is there a recommended approach to reuse filters among different entities in API Platform while adhering to DRY principles?
  • Is there a way to work around the final class constraint to extend or reuse API Platform’s filter logic?
  • Are there any alternative design patterns or strategies for elegantly handling this issue within the Symfony/API Platform ecosystem?

I’m open to any suggestions, even those that might involve reconsidering the current architecture, if it leads to a cleaner and more maintainable solution.

php mysqli buildtree and get count of all children

What I want is to know and count all children recursively for each parent.

  • I have 2 pages: children.php and function.php.
  • In my children.php page I have a table of all parents in the db.
  • in my children.php page I pass each parent to a function to get all
    the children recursively, however the function only return 0.

In children.php I have the following:

$r=mysqli_query($link,"SELECT `id`,`parent_id` FROM locations WHERE parent_id = '0'");
$data = array();
while($row = mysqli_fetch_assoc($r)) 
{
    $data[] = $row;
    $child_id = $row['id'];
    $d = buildtree($data, $child_id);
}
echo count($d);

in function.php I have this code:

function buildtree($src_arr, $parent_id, $tree = array())
{
    foreach($src_arr as $idx => $row)
    {
        if($row['parent_id'] == $parent_id)
        {
            foreach($row as $k => $v)
                $tree[$row['sys_id']][$k] = $v;
            unset($src_arr[$idx]);
            $tree[$row['sys_id']]['children'] = buildtree($src_arr, $row['sys_id']);
        }
    }
    ksort($tree);
    return $tree;
}

So, what I am looking after is to return an array of all children recursively of each parent and echo the count of this array.

Google Client API: Uncaught TypeError: Argument must be an instance of RenderAccountIssuesRequestPayload

Data sources

1)
I use this releas https://github.com/googleapis/google-api-php-client/releases of google client api library – for php 7.4
https://prnt.sc/l-WHG_rzCgGt – this one

2)
And use this samples library https://github.com/googleads/googleads-shopping-samples/tree/main/php to make some requests to my Google Shopping (Google Merchant) account.

My problen IS:

When I try to call such function in my script.php file, it trow the error.

public function get_info($accountId) { $status = $this->session->service->merchantsupport->renderaccountissues( $this->session->merchantId, '{ "contentOption": "CONTENT_OPTION_UNSPECIFIED" }'); return $status; }

The error is:
Fatal error: Uncaught TypeError: Argument 2 passed to GoogleServiceShoppingContentResourceMerchantsupport::renderaccountissues() must be an instance of GoogleServiceShoppingContentRenderAccountIssuesRequestPayload, string given, called in /home/tatam0/tadam/test/php_merchant_api/AccountstatusesSample.php on line 65 and defined in /home/tatam0/tadam/test/php_merchant_api/vendor/google/apiclient-services/src/ShoppingContent/Resource/Merchantsupport.php:54

Here is documentation on this funtcion renderaccountissues()
https://developers.google.com/shopping-content/reference/rest/v2.1/merchantsupport/renderaccountissues

https://prnt.sc/iKGzL5HCHGTx – I did as it says

What does mean “must be an instance of RenderAccountIssuesRequestPayload”? I do not understand, how can I change my php-code to make this funnction work correctly?

I tried to make an object or an array from this ‘{ “contentOption”: “CONTENT_OPTION_UNSPECIFIED” }’, but it does not help.

Please help me convert this PDO code to MSQLi. All my methods failed. I found this, but its not accessible online [closed]

Class Database{
 
    private $server = "mysql:host=localhost;dbname=ecomm";
    private $username = "root";
    private $password = "";
    private $options  = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);
    protected $conn;
    
    public function open(){
        try{
            $this->conn = new PDO($this->server, $this->username, $this->password, $this->options);
            return $this->conn;
        }
        catch (PDOException $e){
            echo "There is some problem in connection: " . $e->getMessage();
        }
 
    }
 
    public function close(){
        $this->conn = null;
    }
 
}

$pdo = new Database();

Please help me get around

fixing login form for PHP

i wonder if someone can help me. I am trying to get this login form to work for my web application. i am using html and php, but I keep getting invalid password even if the values are correct.

i tried to fix this code and it still got the same response. below is the code in question. the way it works is, user enters password held in a database using phpmyadmin. then, if password is correct, user should be able to login, however even if it is correct it still comes back saying invalid.

$Email_Address = $Password = "";
$Email_Address_err = $Password_err = $login_err = "";

//removed code for space reasons
    if (empty(trim($_POST["password"]))) {
        $Password_err = "Please enter your password.";
    } else {
        $Password = trim($_POST["password"]);
    }

    if (empty($Email_Address_err) && empty($Password_err)) {
        // Prepare a select statement
        $sql = "SELECT user_id, Email_Address, password FROM `Login/Register` WHERE Email_Address = ?";

        if ($stmt = mysqli_prepare($conn, $sql)) {
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_Email_Address);

            $param_Email_Address = $Email_Address;
            if (mysqli_stmt_execute($stmt)) {
                // Store result
                mysqli_stmt_store_result($stmt);

                // Check if email exists, if yes then verify password
                if (mysqli_stmt_num_rows($stmt) == 1) {
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $user_id, $Email_Address, $hashed_password);
                    if (mysqli_stmt_fetch($stmt)) {
                        // Verify password
                        if (password_verify($Password, $hashed_password)) {
                            // Password is correct, so start a new session
                            session_start();
                        } else {
                            // Password is not valid
                            $login_err = "Invalid password.";
                        }
//code removed for post reasons
}

if you require any confirmation on the above code i am happy to provide, i am just quite confused why it is not working as, in my opinion, i don’t see any glaringly obvious issues. places where curly brackets or code concerning the email are missing and are alright, as i had to remove irrelevant code to upload this post. apologies for the confusion, this is my first time using this website. any help is appreciated! thank you!

How to additional fields to customize single product in Woocommerce

Well, I have a problem, I am wondering how I can create additional inputs above the “quantity of items” and “add to cart” sections so that the customer can personalize their product for themselves. I’d like to be able to do this myself in my theme without plugins unless any actually meet these goals.

I am wondering if a good choice is to use the ‘woocommerce_before_add_to_cart_button’ hookup? How do I later add the values of these inputs to this product to be able to display them in the order summary?

Currently I have this code that adds the field itself.

Unfortunately, these fields do not display either in the shopping cart, the order summary or the order in the ACP. What am I doing wrong? Is this the right way to go?

function my_personalization_field() {
    $html = '<div class="personalization-field">';
        $html .= '<label for="personalization">Personalization:</label>';
        $html .= '<input type="text" id="personalization" name="my_personalization" />';
    $html .= '</div>';

    echo $html;
}
add_action('woocommerce_before_add_to_cart_button', 'my_personalization_field');


function my_adding_custom_data_in_order_items_meta( $item_id, $values, $cart_item_key ) {
    if ( isset($values['my_personalization']) ) {
        $custom_value = $values['my_personalization'];
        wc_add_order_item_meta($item_id, 'my_personalization', $custom_value );
    }
}
add_action('woocommerce_add_order_item_meta','my_adding_custom_data_in_order_items_meta', 10, 3 );

function my_display_personalization_data_in_cart($product_name, $cart_item, $cart_item_key) {
    if(isset($cart_item['my_personalization'])) {
        $product_name .= '<br><small>Personalization: ' . esc_html($cart_item['my_personalization']) . '</small>';
    }

    return $product_name;
}
add_filter('woocommerce_cart_item_name', 'my_display_personalization_data_in_cart', 10, 3);

nghttp2_option_set_no_rfc9113_leading_and_trailing_ws_validation could not be located in the dynamic link library php-8.3.4extphp_curl.dll

While I am starting apache server from laragon on windows I am getting this error:

The procedure entry point nghttp2_option_set_no_rfc9113_leading_and_trailing_ws_validation could not be located in the dynamic link library F:laragonbinphpphp-8.3.4-Win32-vs16-x64extphp_curl.dll

As it is saying it can’t locate the the dynamic link lybrary in F:laragonbinphpphp-8.3.4-Win32-vs16-x64extphp_curl.dll. But the file is there.

I tried to set the exact location in the php.ini file but did not work.

; The ldap extension must be before curl if OpenSSL 1.0.2 and OpenLDAP is used
; otherwise it results in segfault when unloading after using SASL.
; See https://github.com/php/php-src/issues/8620 for more info.
;extension=ldap

extension=F:laragonbinphpphp-8.3.4-Win32-vs16-x64extphp_curl.dll
;extension=ffi
;extension=ftp

Transform string into and array [closed]

We have the following php string;

$string = '5TW10AA#ABB:5CD01234567TD,5TW10AA#ABB:5CD12345678TD,5TW10AA#ABB:5CD23456789TD,6A140EA#ABH:5CD34567891TD,6A140EA#ABH:5CD45678912TD'

In this string, is a pair of SKU and Serial Number divided by :, and each pair is divided by a ,.

We want to transform this string into an array, where we get the SKU as index and Serial number as values. This is so we can combine multiple Serial Numbers of the same SKU.

We want to load it into a table, so we get the following result;


$array= {
    '5TW10AA#ABB' => '5CD01234567TD , 5CD12345678TD , 5CD23456789TD'
    '6A140EA#ABH' => '5CD34567891TD , 5CD45678912TD'
    };

How can we achieve this?

How to publish service provider to the application in laravel 11

I want to add service provider in laravel 11, but i am not sure how to add it using laravel 11. As previous version of laravel, it is added in config/app.php file, but in laravel 11 it needs to be added in packageServiceProvider file within providers folder.
Below is my code, please tell me where i am wrong..

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;

class PaytmWalletServiceProvider extends ServiceProvider
{

    /**
     * All of the container bindings that should be registered.
     *
     * @var array
     */
    public $bindings = [
        ServerProvider::class => AnandLaravelPaytmWalletPaytmWalletServiceProvider::class,
    ];

    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        //
    }
}

How to organize validation of sending a document from a user in a telegram bot in php (Telegraph/Laravel)? [closed]

Хотел реализовать на отправку пользователем в бот документа xlsx запуск последующих действий тоесть валидацию и тд но не нашел метода для этого в документации.

Необходимо реализовать на отправку сообщения с документом типа xlsx воспроизводить некий миддлварь и потом отправлять документ который мидлварем изменен. Я использую эту либу для работы с телегой через вебхуки, буду признателен если опишите как написать такого рода функцию в хендлере.

Laravel, awaiting response when try to access from VPN connection

Good morning, I have a problem with a Laravel v.10 platform.
Installed as a VMWare virtual machine on Debian 11 with nginx.

If I access from the local network everything works fine.
However, if I try to access via VPN, the request remains in “waiting” until I get a timeout error. I ping the server correctly.
If I try to replace the index.php (in the public folder) with a “echo”, it works fine.
If I try to put an “phpinfo()”, I still have a “waiting”.
It seems that Laravel or php intervenes in the request processing, but I don’t understand where and how.
You can help me?

Thank you

php laravel. The GET method is not supported for route /. Supported methods: HEAD [closed]

Symfony
  
Component
  
HttpKernel
  
Exception
  
MethodNotAllowedHttpException
PHP 8.1.9
10.48.4
The GET method is not supported for route /. Supported methods: HEAD.

Symfony
  
Component
  
HttpKernel
  
Exception
  
MethodNotAllowedHttpException
PHP 8.1.9
10.48.4
The GET method is not supported for route /. Supported methods: HEAD.

enter image description here

No such file error when running npx patch-package

When trying to install Mautic 5.0.3 using Composer, I get the following error when running composer update from the application path /var/www/mautic:

PHP Fatal error: Uncaught Error: Failed opening required ‘/var/www/mautic/app/../autoload.php’ (include_path=’.:/usr/share/php’) in /var/www/mautic/app/console-application.php:20

Stack trace:

#0 /var/www/mautic/bin/console(15): include()

#1 {main}
thrown in /var/www/mautic/app/console-application.php on line 20

Script bin/console mautic:assets:generate handling the generate-assets event returned with error code 255

Script @generate-assets was called via post-update-cmd

The error appears to be given by the command > npx patch-package which prints

patch-package 7.0.2

My folder is /var/www/mautic and file /var/www/mautic/autoload.php doesn’t exist.

How to clear cache of a json file in my Godaddy WordPress website automatically when I update it

So I have a website hosted on Godaddy, where I have a “sellers.json” file, the file updates once in a while using a php script I created to update the phpmyadmin database, all of the CRUD operations work as they should, however, the issue we encounter is that on every database update I have to manually go into /wp-admin and click flush cache.

As a developer, I wanted to create a function that will automaticly flush the cache upon every create/edit/delete, I have came across this function “WP_Object_Cache::flush()”, and tried to use it but it didn’t work for me due to an error.
Is that the function and method that I need? or is there an easier method? Thanks!

WordPress own theme development from 0 and 3rd party plugin .css

Colleagues!

I am making own tourism website using WordPress. I have own design, built from 0.

Main page layout works perfectly and represents mine design wishes idea.

It is shown below:

http://unclealextravel.online/?page_id=98

For selling tours, I use 3rd party plugin called “WP travel”. It works perfectly with general themes, developed by others. But when I switch to mine own theme, there is a problem. Mine own theme does not include correct .css, which belongs to this 3rd party plugin.

http://unclealextravel.online/?ttbm_tour=the-mentalist-tickets-las-vegas

What should I add to functions.php to fix the issue with these 3rd party .css?

Thanks in advance!

BR,

Vadim Turchinovich

Tried to add different combinations of codes to functions.php