How to replace a class with a custom class in php?

Given an external dependency within a [email protected] project (without composer):

interface Contract
{
    public static function getFoo(): string;
}

class ExternalDependency implements Contract
{

    public static function getFoo(): string
    {
        return 'gnarf!';
    }
}

That ExternalDependecy is used in dozen other services like so:

class Service extends ExternalDependency {
}

I want to replace ExternalDependency while changing as little code as possible.

I thought I could make use of a class_alias:

class MyFix implements Contract {
    public static function getFoo(): string {
        return 'Foo';
    }
}

class_alias(MyFix::class, SomeExternalDependency::class);

class Service extends SomeExternalDependency {
}

Yet this will issue a warning:

PHP Warning:  Cannot declare class SomeExternalDependency, because the name is already in use in test.php on line 23

In my contrived example, I could delete the ExternalDependency, then it would work as expected. Yet in my actual use-case, the ExternalDependency is a vendor file that I cannot delete.

How to replace the ExternalDependency with MyFix then?


Example on onlinephp.io


This question is related, yet all its answers are based on extending the to be replaced class or or lack detail.

What is the correct way to create api examples in NelmioApiDocBundle?

If you need to provide several options for incoming or outgoing data, how do you specify `examples’?

You can manually specify fields and their values, but
if I have a DTO model, shouldn’t I make a call to this model for an example?

In php, I tried to do it through a call, the example field accepts string, array, int but not the model.

I also tried using the factory, but you can’t call methods in php attributes.

There is an error

Compile Error: Constant expression contains invalid operations

The only thing that worked fine was the inheritance of OpenAPIAttributesExamples and in my class I made calls and it worked

Example my class (a handwritten example, but like this : ))

<?php  
  
namespace AppDto;  
  
use OpenApiAttributes as OA;  
use OpenApiAttributesExamples;  
use SymfonyComponentSerializerAnnotationGroups;  
  
class AggregatedProductDataSelectExample extends Examples  
{  
    public function __construct(  
        AggregatedProductDataSelect $model,  
        string $example,  
        string $summary,  
    ) {  
        $this->product = $product;  
        $this->is_forecast = $is_forecast;  
        $this->max_price = $max_price;  
  
        parent::__construct(  
            example: $example,  
            summary: $summary,  
            value: $model->toArray()  
        );  
    }  
}

Call

responses: [  
    new OAResponse(  
        response: 200,  
        description: 'Агрегированные данные по продуктам в периоде',  
        content: [  
            new OAJsonContent(  
                examples: [  
                    new AggregatedProductDataSelectExample(  
                        new AggregatedProductDataSelect(  
                            is_forecast: true,  
                            max_price: 1.0,  
                            product: '1',  
                        ),
                        summary: 'test1',
                        example: 'test ...'
                    ),  
                ],  
                properties: [  
                    new OAProperty(  
                        property: 'result',  
                        ref: new Model(type: AggregatedProductDataResponse::class, groups: ["default"])  
                    ),  
                ]  
            ),  
        ]  
    ),  
]

What is the right way to do this?

Usage alert: Total tokens exceeded the threshold using Openai API [closed]

I used following script for generating content by the Openai API.

It uses gpt4o model for content generating. When I define 1000+ words article I get error undefined message is showing, but when I defined below 1000 words then article generates perfectly and does not show any errors.

Recently i checked gpt4o increase their token limit 4096 to 8090.

In this moment, such an error is unexpected. I helped from chatgpt to optimize my prompt.

Same error is showing frequently. How to fix this ?

if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'ai-seo-content-nonce' ) ) {
    wp_send_json_error( [ 'message' => esc_html__( 'Nonce verification failed.', 'super-fast-blog-ai' ) ] );
}
if ( empty( $_POST['title'] ) ) {
    wp_send_json_error( [ 'message' => esc_html__( 'Title is required.', 'super-fast-blog-ai' ) ] );
}

// Sanitize and assign variables
$title       = sanitize_text_field( wp_unslash( $_POST['title'] ) );
$seokeyword  = isset( $_POST['seo_keyword'] ) ? sanitize_text_field( wp_unslash( $_POST['seo_keyword'] ) ) : '';
$metadescrip = isset( $_POST['metades'] ) ? sanitize_text_field( wp_unslash( $_POST['metades'] ) ) : '';
$tlanguage   = isset( $_POST['tlanguage'] ) ? sanitize_text_field( wp_unslash( $_POST['tlanguage'] ) ) : '';
$twstyle     = isset( $_POST['twstyle'] ) ? sanitize_text_field( wp_unslash( $_POST['twstyle'] ) ) : '';
$writone     = isset( $_POST['writone'] ) ? sanitize_text_field( wp_unslash( $_POST['writone'] ) ) : '';
$countWord   = isset( $_POST['countWord'] ) ? sanitize_text_field( wp_unslash( $_POST['countWord'] ) ) : '';
$htaging     = isset( $_POST['htaging'] ) ? sanitize_text_field( wp_unslash( $_POST['htaging'] ) ) : '';
$numberh     = isset( $_POST['numberh'] ) ? sanitize_text_field( wp_unslash( $_POST['numberh'] ) ) : '';
$faqlist     = isset( $_POST['faqlist'] ) ? sanitize_text_field( wp_unslash( $_POST['faqlist'] ) ) : '';
$subheading  = isset( $_POST['subheading'] ) ? sanitize_text_field( wp_unslash( $_POST['subheading'] ) ) : '0';
$this->imageApi = isset( $_POST['imageAPi'] ) ? sanitize_text_field( wp_unslash( $_POST['imageAPi'] ) ) : '';

// If subheading is enabled, ensure htaging and numberh are provided.
if ( '1' === $subheading && ( empty( $htaging ) || empty( $numberh ) ) ) {
    wp_send_json_error( [ 'message' => esc_html__( 'Please provide both the header tag and the number of subheadings if subheading is enabled.', 'super-fast-blog-ai' ) ] );
}

global $wpdb;
try {
    $config = new OpenAIConfig( $this->apikey );
    $client = new OpenAIClient( $config );
  
    $user_word_count  = intval( $countWord );
    // Estimate tokens needed (adjust multiplier if needed)
    $estimated_tokens = intval( $user_word_count * 1.5 );

    // Build the prompt in one frame
    $prompt = [
        [
            'role'    => 'system',
            'content' => esc_html__( 'You are a helpful assistant that generates SEO-friendly content.', 'super-fast-blog-ai' )
        ],
        [
            'role'    => 'user',
            'content' => sprintf(
                esc_html__( 'Generate a detailed article on "%1$s" with at least %2$d words.', 'super-fast-blog-ai' ),
                esc_html( $title ),
                $user_word_count
            )
        ]
    ];

    // Consolidate tone, style, and language instructions if provided
    $settings = [];
    if ( ! empty( $writone ) ) { $settings[] = "tone: " . esc_html( $writone ); }
    if ( ! empty( $twstyle ) ) { $settings[] = "style: " . esc_html( $twstyle ); }
    if ( ! empty( $tlanguage ) ) { $settings[] = "language: " . esc_html( $tlanguage ); }
    if ( ! empty( $settings ) ) {
        $prompt[] = [
            'role'    => 'user',
            'content' => 'Use the following settings: ' . implode( ', ', $settings ) . '.'
        ];
    }

    if ( ! empty( $seokeyword ) ) {
        $prompt[] = [
            'role'    => 'user',
            'content' => 'Include the following SEO keywords: ' . esc_html( $seokeyword )
        ];
    }

    if ( '1' === $faqlist ) {
        $prompt[] = [
            'role'    => 'user',
            'content' => esc_html__( 'Add a FAQ section at the end of the article.', 'super-fast-blog-ai' )
        ];
    }

    if ( '1' === $subheading && ! empty( $htaging ) && ! empty( $numberh ) ) {
        $prompt[] = [
            'role'    => 'user',
            'content' => sprintf(
                esc_html__( 'Include %1$d subheadings using %2$s tags, ensuring each contains relevant keywords.', 'super-fast-blog-ai' ),
                intval( $numberh ),
                esc_html( $htaging )
            )
        ];
    }

    // Final formatting instructions
    $prompt[] = [
        'role'    => 'user',
        'content' => esc_html__( 'Use only <h1>, <h2>, <h3>, <p>, <ul>, <li>, <b>, and <i> HTML tags for formatting.', 'super-fast-blog-ai' )
    ];

    // Call the OpenAI client with the optimized prompt
    $response = $client->chat( $this->aimodel, $prompt, $estimated_tokens );
    $content  = $response['choices'][0]['message']['content'] ?? '';

    if ( ! empty( $content ) ) {
        $post_data = [
            'post_title'   => $title,
            'post_content' => wp_kses( $content, wp_kses_allowed_html( 'post' ) ),
            'post_status'  => 'draft',
            'post_author'  => get_current_user_id(),
            'post_date'    => current_time( 'mysql' ),
        ];

        $post_id = wp_insert_post( $post_data );
        $stringcount = mb_strlen( $content, 'UTF-8' );

        if ( $post_id ) {
            $this->otslf_update_seo_meta_generate( $post_id, $seokeyword, $metadescrip );
            wp_set_post_terms( $post_id, get_option( 'otslf_ot_taxonomy', [] ), 'category' );
            $this->otslf_set_featured_image( $post_id, $title );

            $table_name = $wpdb->prefix . 'slf_schedule_post_title_log';
            $data = [
                'title'     => $title,
                'status'    => 'sameday',
                'postid'    => $post_id,
                'charaters' => $stringcount,
                'modelused' => $this->aimodel,
                'indicat'   => 'yes',
                'log_time'  => current_time( 'mysql' ),
            ];
            $wpdb->insert( $table_name, $data ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery  

            wp_send_json_success( [ 'message' => esc_html__( 'Post published successfully.', 'super-fast-blog-ai' ), 'title' => $title ] );
        } else {
            wp_send_json_error( [ 'message' => esc_html__( 'Failed to insert post.', 'super-fast-blog-ai' ) ] );
        }
    } else {
        wp_send_json_error( [ 'message' => esc_html__( 'Generated content was empty.', 'super-fast-blog-ai' ) ] );
    }
} catch ( Exception $e ) {
    wp_send_json_error( [
        'message' => esc_html__( 'Error: Failed to generate content. Please try again later.', 'super-fast-blog-ai' ),
        'error'   => $e->getMessage()
    ] );
}

How to pass a custom variable to a method in a custom QR Code Generator using Chillerlan QRCode Library?

I am currently trying to program a QR code generator using PHP and the QRCode library from Chillerlan.

I have the following problem: I would like to use different module shapes for the layout of the QR codes.
Here is an excerpt of my code:

class QRSvgWithLogoAndCustomShapes extends QRMarkupSVG {
    protected function module(int $x, int $y, int $M_TYPE): string {
        if (
            !$this->matrix->isDark($M_TYPE)
            // we're skipping the finder patterns here
            || $this->matrix->checkType($x, $y, QRMatrix::M_FINDER)
            || $this->matrix->checkType($x, $y, QRMatrix::M_FINDER_DOT)
        ) {
            return '';
        }

        // return a heart shape (or any custom shape for that matter)
        // return sprintf('M%1$s %2$s m0.5,0.96 l-0.412,-0.412 a0.3 0.3 0 0 1 0.412,-0.435 a0.3 0.3 0 0 1 0.412,0.435Z', $x, $y);
        // return sprintf('M%1$s %2$s a0.5,0.5 0 1,0 0.001,0', $x, $y);
        // return sprintf('M%1$s %2$s l0.2,0.4 l0.45,0.05 l-0.35,0.25 l0.12,0.48 l-0.45,-0.25 l-0.45,0.25 l0.12,-0.48 l-0.35,-0.25 l0.45,-0.05Z', $x, $y);
        
        return sprintf('M%1$s %2$s a0.5,0.5 0 1,0 0.001,0', $x, $y);
    }
}

class QrCodeGenerator {
    public function qrgenerate(string $data, $modulShape, bool $includeLogo = false) {
        $options = new SVGWithLogoAndCustomShapesOptions;
        
        // SVG logo options (see extended class below)
        if ($includeLogo) {
            $options->svgLogo         = TEMPLATE_PATH.'module/home/github.svg'; // logo from: https://github.com/simple-icons/simple-icons
            $options->svgLogoScale    = 0.25;
            $options->svgLogoCssClass = 'qr-logo dark';
        } else {
            // No logo, so we set svgLogo to an empty string
            $options->svgLogo = '';
        }

        $options->version              = -1;
        $options->versionMin           = 1;
        $options->versionMax           = 40;
        $options->outputType           = QROutputInterface::CUSTOM;
        $options->outputInterface      = QRSvgWithLogoAndCustomShapes::class;
        $options->outputBase64         = false;
        $options->eccLevel             = EccLevel::H;

        $options->drawLightModules     = true; // optional, currently has no effect
        $options->svgUseFillAttributes = true; // optional, currently has no effect

        if ($modulShape == 'circular') {
            $options->drawCircularModules  = true; // true = round modules
            $options->circleRadius         = 0.4; // keep the default value, as it looks good
        }

        $options->connectPaths         = true; // optional, leave it as is for now
        // If using round modules, choose which parts should remain square
        $options->keepAsSquare         = [
            QRMatrix::M_FINDER_DARK,
            QRMatrix::M_FINDER_DOT,
            QRMatrix::M_ALIGNMENT_DARK,
        ];

        $qrcode = new QRCode($options);
        $qrImage = $qrcode->render($data);  // Generate the QR code as a PNG image

        $matrix = $qrcode->getMatrix($qrcode); // Read the used version, $matrix->version() gives the version for storing in the DB
        $version = $matrix->version();

        $qrCodeData = [$data, 'version' => $matrix->version(), $modulShape];
        var_dump($qrImage);
        exit;
        return $qrCodeData;
    }
}

Now, I need to use the $modulShape variable inside the protected function module.
How can I achieve this, so that I can check the respective module type via if-else and output the corresponding shape accordingly?

php binary could not be either found or executed. Make sure PHP is installed, and add path

here is the settings.json file on vscodium

{"php.executables": {"v8.3.17": "/usr/bin/php"}}

when I try to run it:

[Error: spawn php ENOENT
at ChildProcess._handle.onexit (node:internal/child_process:285:19)
at onErrorNT (node:internal/child_process:483:16)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)] {
errno: -2,
code: 'ENOENT',
syscall: 'spawn php',
path: 'php',
spawnargs: [
'-dxdebug.mode=off',
'/home/kudo/Documents/php learning/index.php'
]
}

I am on fedora. php is installed. version: 8.3.17

How can avoid PHP json_encode to escape URL when I use it for JSON LD? [duplicate]

I use an array to store my Json Ld content

$arJsonLd = array(
            "@context" => "https://schema.org",
            "@type" => "NewsArticle"
        );

I did search here how to convert a PHP array to Json Ld output and multiple answer pointed me to

json_encode($arJsonLd, JSON_PRETTY_PRINT);

the problem is that URLs get escaped

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "NewsArticle"
 }
 </script>

how can I avoid this? On Json Ld documentation url aren’t escaped

Laravel route returning “No response data for this request” when accessing an image file

I’m working on a Laravel application where I need to serve images stored in the filesystem and display them on a web page. I have defined the following route in web.php:

Route::post('/image/{campaign}/{folder}/{filename}', function ($campaign, $folder, $filename) {
    $path = "private/campaigns-images/campaign-$campaign/$folder/$filename";

    if (!Storage::exists($path)) {
        abort(404);
    }

    $file = Storage::get($path);
    $mimeType = Storage::mimeType($path);
    
    return Response::make($file, 200)->header("Content-Type", $mimeType);
})->name('image.show');

HTML and JavaScript
In my frontend, I’m trying to load and set the image as a background for a Fabric.js canvas using JavaScript:

<div class="mySlides">
    <div class="numbertext">1 / 3</div>
    <img id="background-image" 
        src="{{ route('image.show', ['campaign' => 1, 'folder' => 'images_17', 'filename' => 'DJI_20241105104710_0123_V.JPG']) }}"
        alt="Campaign Image"
        style="width: 100%; max-width: 1200px; height: auto;">
</div>

<canvas id="canvas"></canvas>
const canvas = new fabric.Canvas('canvas');

function setBackgroundImage() {
    const imgElement = document.getElementById('background-image'); 

    if (imgElement) {
        imgElement.onload = function () {
            fabric.Image.fromURL(imgElement.src, function (img) {
                canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
                    scaleX: canvas.width / img.width,
                    scaleY: canvas.height / img.height
                });
            });
        };

        // If the image is already loaded (from cache), trigger onload manually
        if (imgElement.complete) {
            imgElement.onload();
        }
    }
}
window.onload = function () {
    setBackgroundImage();
};

Issue

When I try to access an image via (GET request):
http://127.0.0.1:8000/admin/image/1/images_17/DJI_20241105104710_0123_V.JPG
I get the response “No response data for this request” but if I click on the same link the resource is available

What I’ve Tried
Checked that the file exists using Storage::exists($path), and it does.
Changed the route method from POST to GET, but still no response.
Checked storage/logs/laravel.log but no related errors appear.
Tried return response(‘Test Response’); inside the route, but nothing is displayed..

Turn the description input field of Elementor’s Call-To-Action Widget into a WYSIWYG-field

as the title says, I’m trying to hook into Elementor’s exisiting CTA-widget and turn the existing input field into a WYSIWYG-field by looking at the widget’s structure etc. within elementor pro directory. But somehow nothing happens. If I change it in the plugins source file it works, but sure I want to override it through my functions.php.

I’ve done this for the slides Widget before and that worked well. What am I missing here?

/*
 * Set Elementor > CTA widget description as wysiwyg Text Editor
 */
add_action( 'elementor/element/call-to-action/section_content/before_section_end', function( $widget, $args ) {
    $cta_control = ElementorPlugin::instance()->controls_manager->get_control_from_stack( $widget->get_unique_name(), 'call-to-action' );

    if ( is_wp_error( $cta_control ) ) {
        return;
    }

    $cta_control['fields']['description']['type'] = ElementorControls_Manager::WYSIWYG;

    $widget->update_control( 'call-to-action', $cta_control );
},10 ,2 );

Any help appreciated. Thank you.

Got warning while uploading video file in PHP but not image or audio file [duplicate]

i got warnings when i upload a video file in PHP

This is my HTML code:

<form method=”post” action=”post.php” class=”box” enctype=”multipart/form-data”>

<textarea rows=”5″ cols=”35″ name=”message” placeholder=”content”>

<input type=”file” name=”mediaFile”>
button type=”submit”>Post
</form>

These are the warnings:

`Warning: POST Content-Length of 81138635 bytes exceeds the limit of 41943040 bytes in Unknown on line 0

Warning: Undefined array key “message” in C:xampphtdocspost.php on line 15

Warning: Undefined array key “mediaFile” in C:xampphtdocspost.php on line 24

Warning: Trying to access array offset on value of type null in C:xampphtdocspost.php on line 24`

why i did not get these warnings when i successfully upload a image or audio file in the server?

Laravel Files upload

I’m encountering the following error when attempting to upload an image in my Laravel project:

Error:
IlluminateHttpExceptionsPostTooLargeException

I understand that this issue is related to file size limitations. Based on my research, I modified the following settings in my php.ini file:

post max size
upload max file size
memory limit
After making these changes, I restarted Apache, but the error persists.

What I Have Tried:
Updated php.ini settings (as shown above).
Restarted Apache and MySQL to apply changes.
Checked Laravel configuration to ensure proper file storage settings.
Verified that the correct php.ini file is being modified using

PHP getting data from a XML/XBRL file

I am trying to fetch the data from the following file http://regnskaber.virk.dk/48966882/ZG9rdW1lbnRsYWdlcjovLzAzLzdjLzk0LzFhL2I4LzY5ZGMtNGRhZi04NGE0LTRmNTEyN2UxY2U2MA.xml into php

So i can loop every field thru and fetch the needed data.

I have taken a look at How to parse this XML(XBRL) using Php

but i am still unable to go thru the data :/ can someone please help here.

Hvae tried following How to parse this XML(XBRL) using Php

but with no luck

Applying template formatting using PHPWord [duplicate]

I’ve written a Laravel application that generates content for documents and inserts it into existing Word templates using PHPWord. My desired approach is pretty simple:

  1. I generate the content that I need with Markdown formatting
  2. I write that content to named slots in Word (E.g. ${slot}) using PHPWord’s Template Processing

The issue that I’m experiencing is finding reliable ways to write formatted content such as bulleted lists or applying styles that are pre-existing in the Word document. For example, a markdown section of content might be formatted like this:

# Some heading
A paragraph of text
- Bullet 1
- Bullet 2
Some more text
## A sub-heading
- Bullet 1
- Bullet 2
Some text

I don’t have an easy way of knowing what the format will be before the text is generated, but I need to now insert this into Word. I’ve seen people doing this by adding HTML to sections like here, but I don’t know how to do it using named slots, as my content needs to fit into specific places in the document.

I’ve tried using the HTML route, but to no avail (formatting not applied, issues with special characters and the Word documents not opening). I’ve tried plain text, but that obviously leaves out all my required formatting. My latest approach has been to write the actual HTML tags and then use Copilot in Word to format them, but that is tedious and not automated.

Can someone help me with either:

  1. A better way of telling PHPWord to apply the in-document styles (e.g Heading 1, Heading 2 etc.) to markdown text generated and inserted into an existing template.
  2. Or, a way of programmatically telling Copilot in Word to auto-rewrite all of the content inserted with HTML tags.

Parsing XML snippets contained in a log file

I have a data file from an external source which contains multiple XML snippets (up to 350). Each one starts with a bit of text and then some XML output like this :

2025-02-21 16:45:55,760 - Transaction RUN04-merchtranid1 - Success: <?xml version="1.0" encoding="UTF-8"?>
<payment_response>
  <transaction_type>sale</transaction_type>
  <status>approved</status>
  <recurring_type>initial</recurring_type>
  <unique_id>ccc01a6fb43b45cf38298fee067d1688</unique_id>
  <transaction_id>RUN04-merchtranid1</transaction_id>
  <mode>test</mode>
  <timestamp>2025-02-21T14:45:55Z</timestamp>
  <descriptor>UAT Gen Current UK</descriptor>
  <amount>0</amount>
  <currency>EUR</currency>
  <sent_to_acquirer>true</sent_to_acquirer>
  <scheme_transaction_identifier>485029514074150</scheme_transaction_identifier>
</payment_response>

2025-02-21 16:45:56,704 - Transaction RUN04-merchtranid2 - Success: <?xml version="1.0" encoding="UTF-8"?>
<payment_response>
  <transaction_type>sale</transaction_type>
  <status>approved</status>
  <recurring_type>initial</recurring_type>
  <unique_id>1f293c3166045f645b9ea4aeee755840</unique_id>
  <transaction_id>RUN04-merchtranid2</transaction_id>
  <mode>test</mode>
  <timestamp>2025-02-21T14:45:56Z</timestamp>
  <descriptor>UAT Gen Current UK</descriptor>
  <amount>0</amount>
  <currency>GBP</currency>
  <sent_to_acquirer>true</sent_to_acquirer>
  <scheme_transaction_identifier>MDHMKJSTW</scheme_transaction_identifier>
  <scheme_settlement_date>0129</scheme_settlement_date>
</payment_response>

I need to roll through it with PHP and pick out the <unique_id> and matching <transaction_id> for each transaction. I can do this if it was a properly formatted XML document but this obviously isn’t.

Would really appreciate any ideas ?

Error with Nginx (ERR_TOO_MANY_REDIRECTS) in VPS Hostinger default config WordPress

I’m having a problem with my WordPress hosting on a Hostinger VPS with CloudPanel and NGINX. I’ve tried reinstalling it, it worked for 10 minutes (which is strange) and then it stopped working.

Basically, I try to access the site and I get the following response:
“ERR_TOO_MANY_REDIRECTS”
However, when I access wp-login, I can fill in the username and password, but it just reloads the page.

NGINX Error Log – Nothing
PHP-FPM Error Log – Nothing
WP_LOG – Nothing

This is the default configuration file:

server {
  listen 80;
  listen [::]:80;
  listen 443 quic;
  listen 443 ssl;
  listen [::]:443 quic;
  listen [::]:443 ssl;
  http2 on;
  http3 off;
  ssl_certificate_key /etc/nginx/ssl-certificates/www.casamarx.com.br.key;
  ssl_certificate /etc/nginx/ssl-certificates/www.casamarx.com.br.crt;
  server_name casamarx.com.br;
  return 301 https://www.casamarx.com.br$request_uri;
}

server {
  listen 80;
  listen [::]:80;
  listen 443 quic;
  listen 443 ssl;
  listen [::]:443 quic;
  listen [::]:443 ssl;
  http2 on;
  http3 off;
  ssl_certificate_key /etc/nginx/ssl-certificates/www.casamarx.com.br.key;
  ssl_certificate /etc/nginx/ssl-certificates/www.casamarx.com.br.crt;
  server_name www.casamarx.com.br www1.casamarx.com.br;
  root /home/casamarx/htdocs/www.casamarx.com.br;

  access_log /home/casamarx/logs/nginx/access.log main;
  error_log /home/casamarx/logs/nginx/error.log;

  if ($scheme != "https") {
    rewrite ^ https://$host$request_uri permanent;
  }

  location ~ /.well-known {
    auth_basic off;
    allow all;
  }

  location ~/.git {
    deny all;
  }

  location = /xmlrpc.php {
    deny all;
  }

  location ~/(wp-admin/|wp-login.php) {
    #auth_basic "Restricted Area";
    #auth_basic_user_file /home/site-user/.htpasswd;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8080;
    proxy_max_temp_file_size 0;
    proxy_connect_timeout      7200;
    proxy_send_timeout         7200;
    proxy_read_timeout         7200;
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_temp_file_write_size 256k;
  }

  location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_hide_header X-Varnish;
    proxy_redirect off;
    proxy_max_temp_file_size 0;
    proxy_connect_timeout      720;
    proxy_send_timeout         720;
    proxy_read_timeout         720;
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_temp_file_write_size 256k;
  }

  location ~* ^.+.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|woff2|eot|mp4|ogg|ogv|webm|webp|zip|swf|map)$ {
    # WordPress Multisite Subdirectory
    rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 break;
    rewrite ^/[_0-9a-zA-Z-]+(/.*.php)$ $1 break;
    add_header Access-Control-Allow-Origin "*";
    add_header alt-svc 'h3=":443"; ma=86400';
    expires max;
    access_log off;
  }

  if (-f $request_filename) {
    break;
  }
}

server {
  listen 8080;
  listen [::]:8080;
  server_name www.casamarx.com.br www1.casamarx.com.br;
  root /home/casamarx/htdocs/www.casamarx.com.br;

  include /etc/nginx/global_settings;

  try_files $uri $uri/ /index.php?$args;
  index index.php index.html;

  location ~ .php$ {
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    try_files $uri =404;
    fastcgi_read_timeout 3600;
    fastcgi_send_timeout 3600;
    fastcgi_param HTTPS "on";
    fastcgi_param SERVER_PORT 443;
    fastcgi_pass 127.0.0.1:15001;
    fastcgi_param PHP_VALUE "
    error_log=/home/casamarx/logs/php/error.log;
    memory_limit=512M;
    max_execution_time=60;
    max_input_time=60;
    max_input_vars=10000;
    post_max_size=64M;
    upload_max_filesize=64M;
    date.timezone=UTC;
    display_errors=off;";
  }

  # WordPress Multisite Subdirectory
  if (!-e $request_filename) {
    rewrite /wp-admin$ https://$host$uri permanent;
    rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last;
    rewrite ^/[_0-9a-zA-Z-]+(/.*.php)$ $1 last;
  }

  if (-f $request_filename) {
    break;
  }
}

Portuguese:

Estou passando por um problema com minha hospedagem WordPress em uma VPS do Hostinger com CloudPanel e NGINX. Já tentei reinstalar, funcionou por um tempo de 10 minutos (o que é estranho) e logo em seguida passou a não funcionar.

Basicamente tento entrar no site e meu retorno é:
“ERR_TOO_MANY_REDIRECTS”
Porém, quando entro no wp-login, consigo preencher usuário e senha, mas ele somente recarrega a página.

NGINX Error Log – Não tem nada
PHP-FPM Error Log – Não tem nada
WP_LOG – Não tem nada

I tried to modify the permissions, I tried to disable plugins (at the first occurrence), but nothing. I don’t understand too much about nginx. But, I know when the VPS had the srv….hostinger.cloud (original domain) from Hostinger, don’t currency anything like this error.

Symfony Form: Validate children before parent

I have code that looks more or less like this:

It’s not my actual code, but just to show the concept of what I’m trying to do:

I have a form where each individual field is required and then some checks are run on the values of multiple fields in combination.

class testForm extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault(
            'constraints', 
            [new Callback(
                ['callback' => function (
                        $payload, 
                        ExecutionContextInterface $context
                    ) 
                    {
                        $data = $context->getObject()->getData();

                        if (strcasecmp($data['field1'], $data['field2']))
                        {
                            $context
                                ->buildViolation('fields must be equal')
                                ->atPath('[field1]')
                                ->addViolation();
                        }
                    }
                ]
            )]
        );
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('field1', TextType::class, ['constraints' => [new NotBlank]])
            ->add('field2', TextType::class, ['constraints' => [new NotBlank]]);
    }
}

The problem I’m having with this code is that it will throw a notice when you submit with empty fields (null is not allowed as parameters for string functions like strcasecmp() since PHP 8.0).

AFAICT this is because the parent validation runs before the child validation, so it only checks if the fields have values after the upper level validation has run.

What I am looking for is a way to reverse this, i.e. run the child validation before the parent validation is called. Looking at the Symfony documentation, there’s a Valid constraint that seems to do exactly that, but it only seems to work with entities (my form doesn’t use an entity, but a simple DTO).

So I remain wondering about a way to either make Valid work without entities, or some other way to remedy the constraints of doing this.