Controller returning 500 (Could not denormalize object of type)

I am very much new to Symfony.

I am learning about Controllers here at https://symfony.com/doc/current/controller.html

Controller:

namespace AppController;

use AppModelUserDto;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpKernelAttributeMapQueryString;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentRoutingAttributeRoute;


class QueryController extends AbstractController
{
    #[Route('/query', name: 'app_query')]
    public function index(
        #[MapQueryString] UserDTO $userDto
    ): JsonResponse {
        return $this->json(['dto' => $userDto]);
    }
}

Model:

namespace AppModel;

use SymfonyComponentValidatorConstraints as Assert;

class UserDTO
{
    public function __construct(
        #[AssertNotBlank]
        public string $firstName,

        #[AssertNotBlank]
        public string $lastName,

        #[AssertGreaterThan(18)]
        public int $age,
    ) {
    }
}

But it is throwing the below error.

Could not denormalize object of type “AppModelUserDto”, no
supporting normalizer found.

Symfony Version is 7

How split image about text GD PHP? [closed]

I have image with some text. I want split this image about word or phrase. Please give me any solutions with GD PHP or JS. I must receive array of files .png with parts of basic image. Thank you!

I tried many solutions from internet. May be I simply stupid?

Write shell command to find long if loops within a directory of php files

I have a nested directory of files in php, some of them may have if and else conditions within them

if (condition) {
  // ~100 lines of code
}

I want to quickly find those [files/start of if or else condition] within files that have long bodies within if or else conditions. Say > 100 lines within the flower brackets

Eg:

File1:
    if (condition) {
      // >100 lines of code
    } else {
     // 50 lines of code
    }
    ...
    if (condition) {
      // 10 lines of code
    }
File2:
   if (condition) {
     // 2 lines
   }

should return the line number of the first if condition from File1 because it has 100+ lines within its opening and closing brackets. There could be nested if conditions as well

Product Tags registering programmatically but return page 404 when viewing

I am developing a data synchronisation in wordpress from which I am retrieving the data from a 3rd party api.

The issue that I am facing is that the product tags are being adding programmatically however when I click on view named product_tag .../product_tag/test-tag it returns an page 404.

Product Tag

Weirdly enough, when I go on a product and add the product tag and look up the product tag that I want to add, the tag does not show up (those added programmatically via syncher). Those tags added manually via interface show up in the search.

I have tried:

  • batching the process
  • limit the process
  • added a product tag programmatically (on header.php)
try {
    $tag_name = ucwords(strtolower($product['product_sku']));
    $term = get_term_by('name', $tag_name, 'product_tag');

    if (!$term || is_wp_error($term)) {
        $term = (object) wp_insert_term($tag_name, 'product_tag');
    }

    if (!is_wp_error($term)) {
        $term_id = $term->term_id;
    }

    $add_product_tag = wp_set_object_terms($post_id, $term_id, 'product_tag', true);

} catch (Exception $e) {
    error_log($e->getMessage());
}

I am logging step and it is showing that the data is being stored. I have looked into the database and the data is visible there.

So I am quite confused why it is not working when adding a product_tag programmatically within a syncer process.

Any help is appreciated!

Thank you

Upload custom product to WooCommerce Cart from App

I’ve created a C# Windows client application to create designs of various types, and would like to upload the designs (PDF/Png/etc) to a WooCommerce cart to allow the customer to order professional prints.

How to achieve this in WooCommerce?

For instance, first upload the design to a remote folder accessible from WooCommerce, and then view the cart in the web browser by specifying a custom URL with product ID, custom design ID and thumbnail ID.

add an additional percentage fee on the WooCommerce checkout page problem

By following these questions and answers (Exclude some products from calculated additional fee in WooCommerce) , (Custom checkbox in WooCommerce admin edit product for a payment fee calculation)

these functions work with line_subtotal , The problem is that when we apply a discount code. Also, the additional percentage is considered from the original full price, not from the price shown by deducting the discount code.

I want the additional percentage to be added only on the price of the products (without shipping costs). In case the discount code is not applied, or applied. Add from the rest of the subtotal price of the products.

I used this

// Percentage tax fee for defined payment methods IDs
add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_fee_for_gateway' );
function add_checkout_fee_for_gateway( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    $targeted_payment_methods = array('paypal', 'bacs', 'cheque'); // Define the payment method(s) ID(s)
    
    // Only on checkout page and for specific payment method ID
    if ( is_checkout() && ! is_wc_endpoint_url() 
    && in_array(WC()->session->get('chosen_payment_method'),  $targeted_payment_methods) ) {
        $percentage_rate  = 0.09; // Defined percentage rate
        $custom_subtotal  = 0; // Initializing
        
        // Loop through cart items
        foreach( $cart->get_cart() as $item ) {
            // Get the WC_Product object
            $product = wc_get_product( $item['product_id'] );
            // Check if the product is excluded from fee calculation
            if( $product->get_meta('_tax_fee_excluded') !== 'yes' ) {
                // Calculate items subtotal from non-excluded products
                $custom_subtotal += $product->get_price() * $item['quantity'];
            }
        }

        if ( $custom_subtotal > 0 ) {
            $cart->add_fee( __('9% value added tax'), ($custom_subtotal * $percentage_rate), true, '' );
        }
    }
}

instead of

// Percentage tax fee for defined payment methods IDs
add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_fee_for_gateway' );
function add_checkout_fee_for_gateway( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    $targeted_payment_methods = array('paypal', 'bacs', 'cheque'); // Define the payment method(s) ID(s)
    
    // Only on checkout page and for specific payment method ID
    if ( is_checkout() && ! is_wc_endpoint_url() 
    && in_array(WC()->session->get('chosen_payment_method'),  $targeted_payment_methods) ) {
        $percentage_rate  = 0.09; // Defined percentage rate
        $custom_subtotal  = 0; // Initializing
        
        // Loop through cart items
        foreach( $cart->get_cart() as $item ) {
            // Get the WC_Product object
            $product = wc_get_product( $item['product_id'] );
            // Check if the product is excluded from fee calculation
            if( $product->get_meta('_tax_fee_excluded') !== 'yes' ) {
                // Calculate items subtotal from non excluded products
                $custom_subtotal += (float) $item['line_subtotal'];
            }
        }

        if ( $custom_subtotal > 0 ) {
            $cart->add_fee( __('9% value added tax'), ($custom_subtotal * $percentage_rate), true, '' );
        }
    }
}

But I don’t know if this is true or not. In short, my only problem with the code in the second link above is that when the discount code is applied, the surcharge is not calculated correctly. And everything is fine as long as the discount code is not used.

Why does getenv return 2 items in php-fpm, but many if I call $_SERVER first?

I am using Amazon Linux 2 with apache and php8.2-fpm. I have not tested this on any other linux distro.

If I run the following script via web browser

<?php
var_dump(getenv('PATH'));

it will output something as expected,

string(49) "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"

But if I try use getenv to output all environment variables I get just 2.

<?php
foreach (getenv() as $key => $value)
{
    echo "$key - $value<br />";
}

I will then get

USER - apache
HOME - /usr/share/httpd

but PATH is not here…

Oddly if I change the last example to have $_SERVER just accessed (and modifying $value to be strlen($value) but that is irrelevant to the question.

<?php
$_SERVER;
foreach (getenv() as $key => $value)
{
    echo $key.' - '.strlen($value).'<br />';
}

I now suddenly get ALL of this

USER - 6
HOME - 16
SCRIPT_NAME - 13
REQUEST_URI - 13
QUERY_STRING - 0
REQUEST_METHOD - 3
SERVER_PROTOCOL - 8
GATEWAY_INTERFACE - 7
REMOTE_PORT - 5
SCRIPT_FILENAME - 49
SERVER_ADMIN - 22
CONTEXT_DOCUMENT_ROOT - 36
CONTEXT_PREFIX - 0
REQUEST_SCHEME - 5
DOCUMENT_ROOT - 36
REMOTE_ADDR - 14
SERVER_PORT - 3
SERVER_ADDR - 14
SERVER_NAME - 20
SERVER_SOFTWARE - 6
SERVER_SIGNATURE - 0
PATH - 49
HTTP_HOST - 20
HTTP_COOKIE - 1575
HTTP_ACCEPT_LANGUAGE - 14
HTTP_ACCEPT_ENCODING - 23
HTTP_SEC_FETCH_DEST - 8
HTTP_SEC_FETCH_USER - 2
HTTP_SEC_FETCH_MODE - 8
HTTP_SEC_FETCH_SITE - 4
HTTP_ACCEPT - 135
HTTP_USER_AGENT - 131
HTTP_UPGRADE_INSECURE_REQUESTS - 1
HTTP_DNT - 1
HTTP_SEC_CH_UA_PLATFORM - 7
HTTP_SEC_CH_UA_MOBILE - 2
HTTP_SEC_CH_UA - 65
HTTP_CACHE_CONTROL - 9
proxy-nokeepalive - 1
H2_STREAM_TAG - 4
H2_STREAM_ID - 1
H2_PUSHED_ON - 0
H2_PUSHED - 0
H2_PUSH - 3
H2PUSH - 3
HTTP2 - 2
SSL_TLS_SNI - 20
HTTPS - 2
UNIQUE_ID - 27
FCGI_ROLE - 9
PHP_SELF - 13
REQUEST_TIME_FLOAT - 15
REQUEST_TIME - 10

What’s going on here? I can fetch PATH, but I can’t fetch everything until $_SERVER is touched.

Symfony console issue with Laravel 11

I upgraded my Laravel 8 to 11 (after going through 9 and 10 first), I updated the php version to 8.2 and installed its packages, I updated the composer packages’ version and edited some of the php code where it was required by the documentation … I run composer install and it went well, but, when I run php artisan optimize it threw this error:

PHP Fatal error:  Declaration of SymfonyComponentConsoleStyleOutputStyle::write($messages, bool $newline = false, int $type = self::OUTPUT_NORMAL) must be compatible with SymfonyComponentConsoleOutputOutputInterface::write(Traversable|array|string $messages, bool $newline = false, int $options = 0): void in /home/admin/web/workingexampledomain.com/public_html/vendor/symfony/console/Style/OutputStyle.php on line 52

   SymfonyComponentErrorHandlerErrorFatalError

  Declaration of SymfonyComponentConsoleStyleOutputStyle::write($messages, bool $newline = false, int $type = self::OUTPUT_NORMAL) must be compatible with SymfonyComponentConsoleOutputOutputInterface::write(Traversable|array|string $messages, bool $newline = false, int $options = 0): void

  at /home/admin/web/workingexampledomain.com/public_html/vendor/symfony/console/Style/OutputStyle.php:52
     48▕
     49▕     /**
     50▕      * {@inheritdoc}
     51▕      */
  ➜  52▕     public function write($messages, bool $newline = false, int $type = self::OUTPUT_NORMAL)
     53▕     {
     54▕         $this->output->write($messages, $newline, $type);
     55▕     }
     56▕


   

I tried checking if there is any package that conflicts with the latest version of symfony console but I didn’t find anything.

PHP PHPUnit Test Cases

Write a class ‘Skill’ that handles any function which starts with ‘has_’ keyword return function ‘exist’ and any other function that starts with any word that should return ‘not exist’ and checking a property if it ends with ‘_CT’ return md5 encryption for property otherwise return without encryption.

I have used magic functions and object-oriented programming.

Below are the files with the code for class Skill and test cases:

Skill.php


<?php declare(strict_types=1);

namespace Exam;

class Skill
{
    public function __call($name, $arguments)
    {
        if (strpos($name, 'has_') === 0) {
            return 'exist';
        } else {
            return 'not exist';
        }
    }

    public function __get($name)
    {
        if (substr($name, -3) === '_CT') {
            return md5($name);
        } else {
            return 'not exist';
        }
    }

    public function __toString()
    {
        return 'Skill object';
    }

    public function __set($name, $value)
    {
        $this->$name = $value;
    }

    public function __invoke($args)
    {
        return array_sum($args);
    }
}

SkillTest.php


<?php

use CoalitionExamSkill;
use PHPUnitFrameworkTestCase;

class SkillTest extends TestCase
{
    public function testHasFunctionExists(): void
    {
        $skill = new Skill();
        $function = 'has' . $this->generateRandomString(5);
        $this->assertTrue($skill->$function(), 'success');
    }

    public function testHasPropertyExists(): void
    {
        $skill = new Skill();
        $property = $this->generateRandomString(7) . '_CT';

        $this->assertTrue($skill->$property == md5($property), 'success');
    }
     
    public function testHasAnyPropertyExists(): void
    {
        $skill = new Skill();
        $property = $this->generateRandomString(7);

        $this->assertFalse($skill->$property == md5($property), 'success');
    }

    public function testObjectAsString(): void
    {
        $skill = new Skill();
        $this->assertTrue( strpos($skill, 'CT') !== false, 'success');
    }

    public function testSetSkillLanguage(): void
    {
        $skill = new Skill();
        $skill->language = 'PHP';
        $this->assertTrue( $skill->language === 'PHP', 'success');
    }


    public function testInvoke(): void
    {
        $skill = new Skill();
        $this->assertEquals(10, $skill([3,7]));
    }

    private function generateRandomString($length = 10): string
    {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

}

When I run PHPUnit tests, I am getting 2 failures.

There were 2 failures:

1)

SkillTest::testHasFunctionExists
success
Failed asserting that ‘not exist’ is true.

C:xampphtdocsRizeen-CTtestsSkillTest.php:12

SkillTest::testObjectAsString
success
Failed asserting that false is true.

C:xampphtdocsRizeen-CTtestsSkillTest.php:34

FAILURES!

Tests: 6, Assertions: 6, Failures: 2.

I tried using assertFalse(), but the issue still persists.

type error in website and admin page not oepning [closed]

hey my dear friend when i upload php file to my website it show an error and login panel also not working it show

SentryContextOsContext::__construct(): Argument #1 ($name) must be of type string, null given, called in /home/vol14_4/infinityfree.com/if0_36374154/htdocs/laravel/vendor/sentry/sentry/src/Integration/EnvironmentIntegration.php on line 58
and mirror link : https://flareapp.io/share/B5ZaXK07#top

i try every type of code which is possible and i expect someone help me as soon as possible

recieving 404 not found error after submitting a form

i know it’s a silly issue but I am at the very beginning stage of learning Laravel without any guidance or help from anyone. so please, don’t mind. I’ll delete it after getting the answer.

I am using Laravel with react inertia. i am submitting a form from ‘/p/create’ to ‘/p’ route that is returning me 404 not found error. can’t find what went wrong here.

My routes:

Route::get('/p/create', function () {
    return Inertia::render('Posts');
})->name('posts.create');

Route::post('/p', [PostController::class, 'store']);

my PostController:

<?php

namespace AppHttpControllers;

use AppHttpControllersController;
use IlluminateHttpRequest;

class PostController extends Controller
{

    public function store()
    {
        dd(request()->all())
    }
}

The form of ‘/p/create’


export default function Posts({ auth }) {
    return (
        <div className="post">
            <Navbar auth={auth} />

            <form
                encType="multipart/form-data"
                action="{{ route('posts') }}"
                method="POST"
            >
                <input
                    type="hidden"
                    name="_token"
                    value="{!! csrf_token() !!}"
                />

                <input type="file" name="image" />
                <textarea name="caption" />
                <button type="submit">Post</button>
            </form>
        </div>
    );
}

Second input not working with post method php

I have two input on my html page.I want to process both input with post method.The second input never reach my php script called upload.php it always fall in valid.php which is the first php script processing the first input.

First input

<form method="POST" action="valid.php">
<td style="color:#0a3448;font-size:11px;font-weight:bold;">Your ID :</td>
    <td width="50%"><input type="text" name="id" size="" style="width: 180px"></td>
</tr>
<br>
<td style="color:#0a3448;font-size:11px;font-weight:bold;">ID confirmation : </td>
<td width="0%"><input type="text" name="idconf" size="" style="width: 180px">
<div class="block" id="thoughtbot">
<button>Validate</button> 

Second input

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">

  <input type="submit" value="Upload Image" name="submit">
</form>

How can i make the second input working ?

Data Quality Rules in Redcap

In Redcap, we have instrument called Follow-up , where patients visit on every 3,6,9 months(repeating instance), so while writing Data Quality Rules to find discrepancies in this particular repeating instance how to write a rule(logic). I tried with [date_of_last_followup][1] but this rule is picking even [date_of_last_followup] as discrepancy along with [date_of_last_followup]#1, which it shouldn’t. Instead it should show only [date_of_last_followup]#1

I gave detailed problem which am facing, I want a solution to it

Can’t use Laravel

Failed to download doctrine/inflector from dist: The zip extension and
unzip/7z commands are both missing, skipping.
The php.ini used by your command-line PHP is: C:xamppphpphp.ini

Now trying to download from source

I tried to run the laravel but cant because of the case