Symfony7 shared installations with cross repo and exclusive feature

I am trying to figure out what is the best approach to a reusable symfony application which has this key feature:

  • It uses a company shared private bundle which is being used in different projects (not just copies of the main app)
  • It has the main app which is the reusable one with optional feature that can be enabled via database
  • Each main app installation can have one or more extra feature bundle (which are extra private GIT repository). The key point here is that it may happen that for one installation i may want FeatureA to be in “beta mode” (so let’s say like a develop branch) while some other installation may still want the feature in “stable mode”. This would bring incoherence in my composer.json file and i can’t find any good solution to this issue.

For example let’s say my company shared private bundle is just a set of services that can handle some common utility tasks. The main app can be something like “stock management” then for some reason one installation may be needed to be used as a base for a book store, the other one for a shop center where each one has their own special needs to add extra feature around the base stock management layer

My question are:

  1. Has this approach have any sense at all? If not, what are the alternatives?
  2. If keeping everything separated as i said is doable, how should i handle different composer.json, assets (css/js), templates and more important symfony routes?

I would accept any answer that leads me to a solid, robust and maintainable long-term solution

I tried approaching the issue by creating 3 different repository: the shared private bundle, the main app and the feature bundle but i can’t seem to find the will to continue before i know if the decision made is solid enough to be used as base structure for the project

Performance Regression with Imagick between PHP 7.2 and 8.2

I’m noticing a significant performance difference when running the same Imagick script on PHP 7.2 versus PHP 8.2. Here are the results I’ve gathered:

  • PHP 7.2, ImageMagick 7.0.7, Imagick 3.44: 3.8 seconds

  • PHP 8.2, ImageMagick 7.1, Imagick 3.7: 13.32 seconds

Same spec machine, tested on windows and centos with similar results.

I’m wondering if anyone has encountered similar issues or knows why this change between PHP versions might be affecting Imagick’s performance so drastically? Or know any fixes for this? Below is the test script I’m using (it does this on other functions too not just distorts, this is just an example):

<?php

$startTime = microtime(true);

// Get script directory
$script_path = dirname(__FILE__) . "/";

$controlPoints = [
    1.5,
    0, 0, 355, 70,
    0, 3708, 337, 974,
    1380, 0, 657, 105,
    1380, 3708, 654, 956,
];

echo "Doing Distortion 1n";

$design = new Imagick($script_path . 'input.png');

// Apply distortion
try {
    $design->distortImage(Imagick::DISTORTION_POLYNOMIAL, $controlPoints, true);
} catch (Exception $e) {
    echo "Error applying distortion: " . $e->getMessage() . "n";
}

// Write the distorted image to an output file
$design->writeImage($script_path . "testoutput.png");

$endTime = microtime(true);
$executionTime = ($endTime - $startTime);

echo "Execution Time: " . $executionTime . " secondsn";

PHP variable as reference

I’m confused about the concept of variable in PHP.
As far as I know, a variable in PHP has a name ($p) and a value ('Carlo').

$p has an associated entry in symbol table, such an entry actually points to the memory area where the variable’s value is stored (i.e. the string 'Carlo').

Consider the following:

$n =& $p

$n basically is an alias of $p therefore it points to the memory area where $p points to.

From an “under the hood” viewpoint, does the PHP interpreter create a new entry in symbol table for $nor since it is an alias doesn’t have its own symbol table’s entry ?

Btw, suppose to define class Alpha with its properties and methods. Then does $c = new Alpha actually return a “reference” into the $c variable, in other words is $c value a reference in memory to an instance of class Alpha ?

Anyone has hints about what’s the problem here? – Laravel eager loading

simple example for my question

As you can see in the screenshot, there’s an error detected by Cursor IDE.

I specified the Model Contract as a type for a variable used in the function giveMeAContract.

But the problem is, at the function wtf() context,
the giveMeAContract() function seems to only want laravel query builder rather than a Model.

Problem is, the error message coming from the red underline says that you have to put a Model in it not the query builder. I think it’s exactly opposite of what I did.

Plus, it only happens when I eager load the collection.

Any hint for this? I solved it by a type hinting annotation but it is just temporary I guess.

Issue after Upgrading to Laravel 11: Undefined array key “driver”

I followed all the upgrade guide requirements, but when I run php artisan, I get the following error:

Undefined array key "driver"

  at vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemServiceProvider.php:117
    113▕      * @return bool
    114▕      */
    115▕     protected function shouldServeFiles(array $config)
    116▕     {
  ➜ 117▕         return $config['driver'] === 'local' && ($config['serve'] ?? false);
    118▕     }
    119▕ 
    120▕     /**
    121▕      * Get the default file driver.

I checked the vendor files and found the function responsible:

/**
 * Determine if the disk is serveable.
 *
 * @param  array  $config
 * @return bool
 */
protected function shouldServeFiles(array $config)
{
    return $config['driver'] === 'local' && ($config['serve'] ?? false);
}

To debug, I dumped the $config and got:

array:3 [
  "driver" => "local"
  "root" => "/var/www/html/storage/app"
  "throw" => false
]

When I dd() the full condition, it returns false:

dd($config['driver'] === 'local' && ($config['serve'] ?? false));

If I modify the vendor file to return false, php artisan starts working again—but obviously, modifying vendor files isn’t a proper solution.

My filestems.php file

        's3' => [
            'blog' => [
                'driver' => 's3',
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
                'region' => env('AWS_DEFAULT_REGION'),
                'bucket' => 'blog',
                'url' => env('AWS_URL').'/blog',
                'endpoint' => env('AWS_ENDPOINT'),
                'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', true),
                'throw' => true,
            ],
            'verifications' => [
                'driver' => 's3',
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
                'region' => env('AWS_DEFAULT_REGION'),
                'bucket' => 'verifications',
                'url' => env('AWS_URL').'/verifications',
                'endpoint' => env('AWS_ENDPOINT'),
                'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', true),
                'throw' => true,
            ],
            'contracts' => [
                'driver' => 's3',
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
                'region' => env('AWS_DEFAULT_REGION'),
                'bucket' => 'contracts',
                'url' => env('AWS_URL').'/contracts',
                'endpoint' => env('AWS_ENDPOINT'),
                'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', true),
                'throw' => true,
            ],
            'preliminary' => [
                'driver' => 's3',
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
                'region' => env('AWS_DEFAULT_REGION'),
                'bucket' => 'preliminary',
                'url' => env('AWS_URL').'/preliminary',
                'endpoint' => env('AWS_ENDPOINT'),
                'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', true),
                'throw' => true,
            ],
            'temporary' => [
                'driver' => 's3',
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
                'region' => env('AWS_DEFAULT_REGION'),
                'bucket' => 'temporary',
                'url' => env('AWS_URL').'/temporary',
                'endpoint' => env('AWS_ENDPOINT'),
                'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', true),
                'throw' => true,
            ],
            'internal' => [
                'driver' => 's3',
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
                'region' => env('AWS_DEFAULT_REGION'),
                'bucket' => 'internal',
                'url' => env('AWS_URL').'/internal',
                'endpoint' => env('AWS_ENDPOINT'),
                'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', true),
                'throw' => true,
            ],
            'listing-images' => [
                'driver' => 's3',
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
                'region' => env('AWS_DEFAULT_REGION'),
                'bucket' => 'listing-images',
                'url' => env('AWS_URL').'/listing-images',
                'endpoint' => env('AWS_ENDPOINT'),
                'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', true),
                'throw' => true,
            ],
            'payout-invoices' => [
                'driver' => 's3',
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
                'region' => env('AWS_DEFAULT_REGION'),
                'bucket' => 'payout-invoices',
                'url' => env('AWS_URL').'/payout-invoices',
                'endpoint' => env('AWS_ENDPOINT'),
                'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', true),
                'throw' => true,
            ],
            'listing-payment-invoices' => [
                'driver' => 's3',
                'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
                'region' => env('AWS_DEFAULT_REGION'),
                'bucket' => 'listing-payment-invoices',
                'url' => env('AWS_URL').'/listing-payment-invoices',
                'endpoint' => env('AWS_ENDPOINT'),
                'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', true),
                'throw' => true,
            ],
        ],

Has anyone encountered this issue before? Any insights on how to fix it properly?

Need to enable wincache DLL extension into IIS & PHP 8.3 version?

We are trying to install & enable the wincache dll extension into PHP 8.3 version but it is not enable. We added the file and enable extension=php_wincache.dll in php.ini file. But, when we see the PHP info, the wincache modules is not show in the details.

Php version :8.3.19 NTS (non thread safe)
Windows IIS

Could you please provide us non thread safe wincache DLL file and provide the points to install into the IIS server (PHP 8.3)

Thanks,

Create shortcode for each dimension property based on product ID in WooCommerce

Summarize:
Woocommerce product dimensions are length, width and height
Scope of this question is to create a shortcode for each product dimension property individually based on product ID.

Problem:
I found many sources and no one split the dimensions in three single shortcode attribute, like in Display WooCommerce Product Dimensions via a Shortcode answer thread.

This is an example on how Display WooCommerce Product Dimensions via a Shortcode.
I don’t know how to show attribute in near.

Description:
Add where needed a shortcode for Lenght
[user_meta id="35" key="lenght"]
Add where needed a shortcode for Width
[user_meta id="35" key="width"]
Add where needed a shortcode for Height
[user_meta id="35" key="height"]

Expections:
Something like this with a shortcode foreach dimensions

add_action( 'woocommerce_after_shop_loop_item', 'aman_show_product_dimensions', 20 );
  
function aman_show_product_dimensions() {
   global $product;
   $dimensions = $product->get_dimensions();
   if ( ! empty( $dimensions ) ) {
      echo '<div class="dimensions"><b>Height:</b> ' . $product->get_height() . get_option( 'woocommerce_dimension_unit' );
      echo '<br><b>Width:</b> ' . $product->get_width() . get_option( 'woocommerce_dimension_unit' );
      echo '<br><b>Length:</b> ' . $product->get_length() . get_option( 'woocommerce_dimension_unit' );
      echo '</div>';        
   }
}

PHP Leaf framework – db()->lastInsertId() returns “0”

I have issue with PHP Leaf framework database operation which returns “0” instead of last inserted record id.

My PHP version is 8.2.12.

There is a code.

app/routes/__app.php

app()->get('/apiv1/test', function () {
    $res = db()
    ->insert('item_schemas')
    ->params([
        'table_name' => 'hat',
        'created_at' => Carbon::now(),
        'updated_at' => null
    ])->execute();

    $itemSchemaId = db()->lastInsertID();

    response()->json([
        'itemSchemaId' => $itemSchemaId,
        'errors' => $res ? 'No errors' : db()->errors(),
        'res' => $res
    ]);
});

public/index.php

<?php

/*
|--------------------------------------------------------------------------
| Switch to root path
|--------------------------------------------------------------------------
|
| Point to the application root directory so leaf can accurately
| resolve app paths.
|
*/
chdir(dirname(__DIR__));

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require dirname(__DIR__) . '/vendor/autoload.php';

/*
|--------------------------------------------------------------------------
| Bring in (env)
|--------------------------------------------------------------------------
|
| Quickly use our environment variables
|
*/
try {
    DotenvDotenv::createUnsafeImmutable(dirname(__DIR__))->load();
} catch (Throwable $th) {
    trigger_error($th);
}

/*
|--------------------------------------------------------------------------
| Load application paths
|--------------------------------------------------------------------------
|
| Decline static file requests back to the PHP built-in webserver
|
*/
if (php_sapi_name() === 'cli-server') {
    $path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

    if (is_string($path) && __FILE__ !== $path && is_file($path)) {
        return false;
    }

    unset($path);
}

/*
|--------------------------------------------------------------------------
| Attach blade view
|--------------------------------------------------------------------------
|
| Templating has been disabled because you chose the MVC for APIs starter.
| If you want to use blade in your application,
| you can uncomment the line below.
|
*/
// LeafConfig::attachView(LeafBlade::class);

/*
|--------------------------------------------------------------------------
| Load Leaf configuration
|--------------------------------------------------------------------------
|
| Leaf MVC allows you to customize Leaf and it's modules using
| configuration files defined in the config folder. This line
| loads the configuration files and makes them available to
| your application.
|
*/
LeafCore::loadApplicationConfig();




/*
|--------------------------------------------------------------------------
| Sync Leaf Db with ORM and connect
|--------------------------------------------------------------------------
|
| Sync Leaf Db with ORM and connect to the database
| This allows you to use Leaf Db without having
| to initialize it in your controllers.
|
| If you want to use a different connection from those
| used in your models, you can remove the line below and
| add your own connection with:
| db()->connect(...)
|
| **Uncomment the line below to use Leaf Db**
| **You don't need this line to use Leaf Auth**
*/

db()->autoConnect();

/*
|--------------------------------------------------------------------------
| Load custom libraries
|--------------------------------------------------------------------------
|
| You can load your custom libraries here. If you have
| anything defined in your lib folder, you can load
| them here. Simply uncomment the line below.
|
*/
// LeafCore::loadLibs();

/*
|--------------------------------------------------------------------------
| Run your Leaf MVC application
|--------------------------------------------------------------------------
|
| This line brings in all your routes and starts your application
|
*/

LeafCore::runApplication();

composer.json

{
    "name": "leafs/mvc",
    "version": "3.9.1",
    "description": "A lightweight PHP MVC framework powered by Leaf",
    "type": "library",
    "keywords": [
        "framework",
        "leaf",
        "leafPHP",
        "mvc",
        "leaf mvc"
    ],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Darko",
            "email": "[email protected]",
            "homepage": "https://mychi.netlify.app",
            "role": "Maintainer"
        },
        {
            "name": "Abdulbasit Rubeya",
            "email": "[email protected]",
            "homepage": "https://github.com/ibnsultan",
            "role": "Maintainer"
        }
    ],
    "require": {
            "leafs/blade": "*",
            "leafs/mvc-core": "^1.11",
            "leafs/leaf": "^3.7",
            "leafs/csrf": "*",
            "leafs/logger": "v2.0",
            "leafs/cors": "*",
            "leafs/auth": "^3.0",
            "leafs/db": "*",
            "leafs/vite": "^0.3.0",
            "leafs/form": "^3.0",
            "leafs/http": "^3.0",
            "leafs/aloe": "^2.3",
            "leafs/fs": "v2.0"
    },
    "require-dev": {
        "fakerphp/faker": "^1.16",
        "leafs/alchemy": "^2.0"
    },
    "autoload": {
        "psr-4": {
            "App\": "app/",
            "Tests\": "tests/",
            "Config\": "config/",
            "App\Http\": "app/http/",
            "App\Jobs\": "app/jobs/",
            "App\Lang\": "app/lang/",
            "App\Mail\": "app/mail/",
            "App\Views\": "app/views/",
            "App\Utils\": "app/utils/",
            "App\Events\": "app/events/",
            "App\Models\": "app/models/",
            "App\Mailers\": "app/mailers/",
            "App\Workers\": "app/workers/",
            "App\Console\": "app/console/",
            "App\Scripts\": "app/scripts/",
            "App\Helpers\": "app/helpers/",
            "App\Channels\": "app/channels/",
            "App\Services\": "app/services/",
            "App\Middleware\": "app/middleware/",
            "App\Components\": "app/components/",
            "App\Controllers\": "app/controllers/",
            "App\Notifications\": "app/notifications/",
            "App\Database\Seeds\": "app/database/seeds/",
            "App\Database\Schema\": "app/database/schema/",
            "App\Database\Factories\": "app/database/factories/"
        },
        "exclude-from-classmap": [
            "app/database/migrations"
        ]
    },
    "config": {
        "optimize-autoloader": true,
        "sort-packages": false,
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r "file_exists('.env') || copy('.env.example', '.env');"",
            "@php -r "if (file_exists('README2.MD')) {unlink('README.MD'); rename('README2.MD', 'README.MD');}""
        ],
        "post-create-project-cmd": [
            "@php leaf key:generate"
        ]
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

app/database/migrations/2025_03_18_075024_create_item_schema.php

<?php

use LeafDatabase;
use IlluminateDatabaseSchemaBlueprint;

class CreateItemSchema extends Database
{
    /**
     * Run the migrations.
     * @return void
     */
    public function up()
    {
        if (!static::$capsule::schema()->hasTable('item_schemas')) :
            static::$capsule::schema()->create('item_schemas', function (Blueprint $table) {
                $table->id();
                $table->string('table_name')->unique();
                $table->timestamp('created_at')->nullable();
                $table->timestamp('updated_at')->nullable();
            });
        endif;
    }

    /**
     * Reverse the migrations.
     * @return void
     */
    public function down()
    {
        static::$capsule::schema()->dropIfExists('item_schemas');
    }
}

all composer packages after command

composer show -i

carbonphp/carbon-doctrine-types  2.1.0    Types to use Carbon in Doctrine
doctrine/cache                   2.2.0    PHP Doctrine Cache library is a popular cache implementation that suppor...
doctrine/dbal                    3.9.4    Powerful PHP database abstraction layer (DBAL) with many features for da...
doctrine/deprecations            1.1.4    A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 loggin...
doctrine/event-manager           2.0.1    The Doctrine Event Manager is a simple PHP event system that was built t...
doctrine/inflector               2.0.10   PHP Doctrine Inflector is a small library that can perform string manipu...
fakerphp/faker                   v1.24.1  Faker is a PHP library that generates fake data for you.
firebase/php-jwt                 v6.11.0  A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Shou...
graham-campbell/result-type      v1.1.3   An Implementation Of The Result Type
illuminate/bus                   v8.83.27 The Illuminate Bus package.
illuminate/collections           v8.83.27 The Illuminate Collections package.
illuminate/container             v8.83.27 The Illuminate Container package.
illuminate/contracts             v8.83.27 The Illuminate Contracts package.
illuminate/database              v8.83.27 The Illuminate Database package.
illuminate/events                v8.83.27 The Illuminate Events package.
illuminate/filesystem            v8.83.27 The Illuminate Filesystem package.
illuminate/macroable             v8.83.27 The Illuminate Macroable package.
illuminate/pipeline              v8.83.27 The Illuminate Pipeline package.
illuminate/support               v8.83.27 The Illuminate Support package.
illuminate/view                  v8.83.27 The Illuminate View package.
jenssegers/blade                 v1.4.0   The standalone version of Laravel's Blade templating engine for use outs...
leafs/alchemy                    2.2      Integrated testing/style fixing tool for your PHP apps
leafs/aloe                       2.5.1    Overpowered command line tool for your leaf apps.
leafs/anchor                     v1.6.2   Leaf PHP util module
leafs/auth                       v3.4.1   Leaf PHP auth helper
leafs/blade                      v4.0     Leaf PHP Framework adaptation of jenssegers/blade package
leafs/cors                       v1.2     Leaf PHP cors config
leafs/csrf                       v0.5.4   Leaf CSRF security patch for leaf anchor
leafs/date                       v2.2     Leaf PHP date module
leafs/db                         v4.0.1   Leaf PHP db module.
leafs/exception                  v3.6.3   Error handler for leaf (fork of whoops)
leafs/form                       v3.2     Simple straightup data validation
leafs/fs                         v2.0     Leaf PHP session + flash modules
leafs/http                       v3.5     Http abstraction for Leaf PHP
leafs/leaf                       v3.12    Elegant PHP for modern developers
leafs/logger                     v2.0     Leaf PHP logger utility
leafs/mvc-core                   v1.11.1  Core files specific to MVC based leaf frameworks like Leaf MVC and Leaf ...
leafs/password                   v1.0     Leaf PHP password helper
leafs/session                    v4.0.1   Leaf PHP session + flash modules
leafs/vite                       v0.3.0   Server component for Vite
nesbot/carbon                    2.73.0   An API extension for DateTime that supports 281 different languages.
nikic/php-parser                 v4.19.4  A PHP parser written in PHP
phpoption/phpoption              1.9.3    Option Type for PHP
psr/cache                        3.0.0    Common interface for caching libraries
psr/clock                        1.0.0    Common interface for reading the clock.
psr/container                    1.1.2    Common Container Interface (PHP FIG PSR-11)
psr/log                          2.0.0    Common interface for logging libraries
psr/simple-cache                 1.0.1    Common interfaces for simple caching
psy/psysh                        v0.11.22 An interactive shell for modern PHP.
symfony/console                  v5.4.47  Eases the creation of beautiful and testable command line interfaces
symfony/deprecation-contracts    v3.5.1   A generic function and convention to trigger deprecation notices
symfony/finder                   v5.4.45  Finds files and directories via an intuitive fluent interface
symfony/polyfill-ctype           v1.31.0  Symfony polyfill for ctype functions
symfony/polyfill-intl-grapheme   v1.31.0  Symfony polyfill for intl's grapheme_* functions
symfony/polyfill-intl-normalizer v1.31.0  Symfony polyfill for intl's Normalizer class and related functions
symfony/polyfill-mbstring        v1.31.0  Symfony polyfill for the Mbstring extension
symfony/polyfill-php73           v1.31.0  Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions
symfony/polyfill-php80           v1.31.0  Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions
symfony/process                  v6.4.19  Executes commands in sub-processes
symfony/service-contracts        v3.5.1   Generic abstractions related to writing services
symfony/string                   v6.4.15  Provides an object-oriented API to strings and deals with bytes, UTF-8 c...
symfony/translation              v6.4.19  Provides tools to internationalize your application
symfony/translation-contracts    v3.5.1   Generic abstractions related to translation
symfony/var-dumper               v6.4.18  Provides mechanisms for walking through any arbitrary PHP variable
symfony/yaml                     v6.4.18  Loads and dumps YAML files
vlucas/phpdotenv                 v5.6.1   Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SE...
voku/portable-ascii              1.6.1    Portable ASCII library - performance optimized (ascii) string functions ...

And result is:

{
  "itemId": "0"
}

MySQL connection is established correct and record is inserted to the database, db()->lastInsertId() should returns valid record Id. Thanks very much for help.

EDIT:

Result after var_dump:

object(PDOStatement)#36 (1) {
  ["queryString"]=>
  string(78) "INSERT INTO item_schemas (table_name,created_at,updated_at) VALUES (?,?,?)"
}

API result:

{
"itemSchemaId": "0",
  "errors": "No errors",
  "res": {
    "queryString": "INSERT INTO item_schemas 
    (table_name,created_at,updated_at) VALUES (?,?,?)"
  }
}

After Explain query:

"query": [
{
  "id": 1,
  "select_type": "INSERT",
  "table": "item_schemas",
  "partitions": null,
  "type": "ALL",
  "possible_keys": null,
  "key": null,
  "key_len": null,
  "ref": null,
  "rows": null,
  "filtered": null,
  "Extra": null
}
],

Explain query:

$query = db()->query("EXPLAIN " . "INSERT INTO item_schemas (table_name,created_at,updated_at) VALUES ('glovesssssssssssssssdsssss','2025-03-23 10:29:29',NULL)")->all();

Table structure with EXPLAIN:

{
"query": [
{
"Field": "id",
"Type": "bigint(20) unsigned",
"Null": "NO",
"Key": "PRI",
"Default": null,
"Extra": "auto_increment"
},
{
"Field": "table_name",
"Type": "varchar(255)",
"Null": "NO",
"Key": "UNI",
"Default": null,
"Extra": ""
},
{
"Field": "created_at",
"Type": "timestamp",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "updated_at",
"Type": "timestamp",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
}
}

Datatables Server Side Filtering Wrong When Have Space Character

Hello i create datatables serverside with PHP, but filtering result is wrong.
i want to show only 1 data, when i filter “epic 5” but the result show 5 data.
You can check my screenshot here : https://i.ibb.co.com/4RnRcwLg/Screenshot-1.png

When i debug SQL code show like this. Why datatables split my filtering?

SELECT
    `rank_star`.*,
    `rk`.`rank_name`,
    `usr`.`employee_username` 
FROM
    `rank_star`
    LEFT JOIN `rank` AS `rk` ON `rk`.`id_rank` = `rank_star`.`id_rank`
    LEFT JOIN `employee` AS `usr` ON `usr`.`employee_id` = `rank_star`.`created_by`
    LEFT JOIN `employee` AS `usr_up` ON `usr_up`.`employee_id` = `rank_star`.`updated_by` 
WHERE
    (
        LOWER( `rk`.`rank_name` ) LIKE % epic % 
        OR LOWER( `rank_star`.`rank_name_star` ) LIKE % epic % 
        OR LOWER( `rank_star`.`rank_star_order` ) LIKE % epic % 
        OR LOWER( `rank_star`.`created_at` ) LIKE % epic % 
        OR LOWER( `rank_star`.`updated_at` ) LIKE % epic % 
        OR LOWER( `usr`.`employee_username` ) LIKE % epic % 
    OR LOWER( `usr_up`.`employee_username` ) LIKE % epic %) 
    AND (
        LOWER( `rk`.`rank_name` ) LIKE % 5 % 
        OR LOWER( `rank_star`.`rank_name_star` ) LIKE % 5 % 
        OR LOWER( `rank_star`.`rank_star_order` ) LIKE % 5 % 
        OR LOWER( `rank_star`.`created_at` ) LIKE % 5 % 
        OR LOWER( `rank_star`.`updated_at` ) LIKE % 5 % 
        OR LOWER( `usr`.`employee_username` ) LIKE % 5 % 
    OR LOWER( `usr_up`.`employee_username` ) LIKE % 5 %) 
ORDER BY
    `rank_star`.`rank_star_order` ASC 
    LIMIT 100 OFFSET 0

This is my javasript code

$(document).ready(function(){
    $("#example").DataTable({
        search: { "bSmart": false, "bRegex": true },
        serverSide : true,
        processing : true,
        ajax : {
            url : "rank_star/res",
            type : 'POST',
            dataType : 'JSON',
            data : {_token : '{{csrf_token()}}'}
        },
        columns : [
            {data : 'act', name : 'act'},
            {data : 'rank_name', name : 'rk.rank_name'},
            {data : 'rank_name_star', name : 'rank_star.rank_name_star'},
            {data : 'rank_min_star', name : 'rank_min_star',className: "text-center"},
            {data : 'rank_max_star', name : 'rank_max_star',className: "text-center"},
            {data : 'rank_star_order', name : 'rank_star.rank_star_order',className: "text-center"},
            {data : 'created_date', name : 'created_at'},
            {data : 'updated_date', name : 'updated_at'},
            {data : 'employee_add', name : 'usr.employee_username'},
            {data : 'employee_update', name : 'usr_up.employee_username'},
        ],
        pageLength: 100,
        order: [[5, 'asc']],
    });
});

And this is my PHP Code

$data = RankStar::query()->select(
                                [
                                 'rank_star.*',
                                 'rk.rank_name',
                                 'usr.employee_username',
                                ]
                            )
                            ->leftJoin('rank as rk', 'rk.id_rank', '=', 'rank_star.id_rank')
                            ->leftJoin('employee as usr', 'usr.employee_id', '=', 'rank_star.created_by')
                            ->leftJoin('employee as usr_up', 'usr_up.employee_id', '=', 'rank_star.updated_by');
        return datatables()->eloquent($data)
        ->addColumn("act", function($row){

            $func_action ="";
            $btn_edit    = "<button type='button' title='Update' class='btn btn-primary btn-sm' onclick='do_edit("".$row->id_rank_star."")' data-toggle='modal' data-target='#update_modal'><i class='fa fa-pencil'></i></button>&nbsp;";
            $btn_delete  = "<button type='button' title='Delete' class='btn btn-danger btn-sm' onclick='do_delete("".$row->id_rank_star."")'><i class='fa fa-trash'></i></button>";
            
            if(acc_update(Session::get('ses_level'),$this->data['id_menu']) == '1'){
                     $func_action .= $btn_edit;
            }

            if(acc_delete(Session::get('ses_level'),$this->data['id_menu']) == '1'){
                    $func_action .= $btn_delete;
            }

            return "<center>".$func_action."</center>"; 
        })
        ->addColumn("rank_name", function($row){
            return @$row->rank_name;
        })
        ->addColumn("rank_name_star", function($row){
            return @$row->rank_name_star;
        })
        ->addColumn("rank_min_star", function($row){
            return @$row->rank_min_star;
        })
        ->addColumn("rank_max_star", function($row){
            return @$row->rank_max_star;
        })
        ->addColumn("rank_star_order", function($row){
            return @$row->rank_star_order;
        })
        ->addColumn("employee_add", function($row){
            return @$row->creator->employee_username;
        })
        ->addColumn("employee_update", function($row){
            return @$row->updater->employee_username;
        })
        ->addColumn("created_date", function($row){
            return get_date_indonesia($row->created_at)." ".substr($row->created_at, 10, 9);
        })
        ->addColumn("updated_date", function($row){
            return get_date_indonesia($row->updated_at)." ".substr($row->updated_at, 10, 9);
        })
        ->rawColumns(['act'])
        ->make(true);

Help me sir, thanks.

How to get isset() to execute MORE than once in PHP? [duplicate]

I’m trying to do something that should be simple. I want a button that every time it’s clicked to update an mysql row value to increment by 1. so click in ten times and the value is 10. I am trying to use isset() to do this, with just normal variables to test:

php:

   $amount = 0;

   if(isset($_POST['button1'])) {
   echo "button 1 clicked";
   $amount++;
   }

html:

<form method="post">
    <input class="button" type="submit" value="select" name="button1"></input>
</form>

<h1><?= $amount ?></h1>

this works, but only once. My thought was that since $_POST[‘button1’] is now set, it doesn’t execute again because it is only supposed to execute when the value is no longer null and that only happens once. so, I thought I’d try:

   unset($_POST[‘button1’]);

in the isset() block, or even:

   $_POST[‘button1’] = null;

so that the button click would hopefully redefine it, but no luck. what do I do? most questions want a button to click only once, but I want the opposite, for it to theoretically click forever. why can’t a button just call a function like in js? I know php probably isn’t the best choice for this kind of project, but is there a way?

FCM Auth2 subscribe to topic erro: Authentication using

I am trying to send a notification to a group of devices (topic) usin Auth2.
So first I tried to send a message to single device, and it worked OK.

Now I want to create the topic.
So I use this code that is attached at the bottom, but I get the result:

result= {“error”:”Authentication using server key is deprecated. Please use an OAuth2 token instead.”}

The access-token is the same as I use for sending one message.

The code:

$topic="{$card_id}_{$type}_{$locale}";
$url = "https://iid.googleapis.com/iid/v1:batchAdd";
$json=["to" => "/topics/{$topic}", "registration_tokens" => [$fcm_token]];
$result=send_2_FCM($json,$url);
function send_2_FCM($data,$url)
{
  require_once('firebase_access_token.php');
  $access_token=getAccessToken();

  $headers = array(
    "Authorization: Bearer $access_token",
    "Content-Type: application/json"
  );

  $ch = curl_init();
  curl_setopt( $ch,CURLOPT_URL,$url);
  curl_setopt( $ch,CURLOPT_POST,true);
  curl_setopt( $ch,CURLOPT_HTTPHEADER,$headers);
  curl_setopt( $ch,CURLOPT_RETURNTRANSFER,true);
  curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER,false);
  curl_setopt( $ch,CURLOPT_CAINFO, "cacert.pem");
  if ($data)
  {
    curl_setopt( $ch,CURLOPT_POSTFIELDS,json_encode($data));
  }
  $result = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  debug_log("send_2_FCM: result= $result");
  if ($result && strpos($result,'"error"')) return 0;
  return 1;
}

Failed to Generate UUID for ETX Receipt php

Issue: Error Creating UUID for ETX Receipt

Problem Statement:Despite following all the instructions provided by the source for generating a UUID for an ETX receipt, errors persist during the process.

Source Instructions Followed:The UUID generation steps were taken from the official guidelines available at:ETA Receipt Issuance FAQ – UUID Generation

Steps Taken:

Implemented the UUID generation logic as per the provided documentation.

Ensured all required parameters were correctly formatted and included.

Verified system date, time, and unique transaction identifiers.

Checked for any potential conflicts or duplicate values.

Attempted multiple runs with different test cases.

Encountered Errors:

Error messages related to UUID creation.

Request for Assistance:Seeking guidance on:

Debugging methods for UUID generation errors.

Confirming the correct implementation of the required format.

Understanding any additional requirements not explicitly mentioned in the documentation.

Any insights or solutions from those who have successfully generated UUIDs for ETX receipts would be greatly appreciated.

    /////// receiptData
    
    
    $date_now = gmdate("Y-m-dTH:i:sZ");
    
    
    $receiptData = [
       "header" => [
                    "dateTimeIssued" => $date_now,
                    "receiptNumber" => "11111",
                    "uuid" => "",
                    "previousUUID" => "",
                    "referenceOldUUID" => "",
                    "currency" => "EGP",
                    "exchangeRate" => 0,
                    "sOrderNameCode" => "sOrderNameCode",
                    "orderdeliveryMode" => "",
                    "grossWeight" => 6.58,
                    "netWeight" => 6.89
                ],
                "documentType" => [
                    "receiptType" => "S",
                    "typeVersion" => "1.2"
                ],
                "seller" => [
                    "rin" => "249628635",
                    "companyTradeName" => "Mahmoud Mahros",
                    "branchCode" => "0",
                    "branchAddress" => [
                        "country" => "EG",
                        "governate" => "cairo",
                        "regionCity" => "city center",
                        "street" => "16 street",
                        "buildingNumber" => "14BN",
                        "postalCode" => "74235",
                        "floor" => "1F",
                        "room" => "3R",
                        "landmark" => "tahrir square",
                        "additionalInformation" => "talaat harb street"
                    ],
                    "deviceSerialNumber" => "100010001010",
                    "syndicateLicenseNumber" => "100010001010",
                    "activityCode" => "4922"
                ],
                "buyer" => [
                    "type" => "P",
                    "id" => "29308263200032",
                    "name" => "mahmoud mahros",
                    "mobileNumber" => "+201020567462",
                    "paymentNumber" => "987654"
                ],
                "itemData" => [
                    [
                        "internalCode" => "880609",
                        "description" => "Samsung A02 32GB_LTE_BLACK_DS_SM-A022FZKDMEB_A022 _ A022_SM-A022FZKDMEB",
                        "itemType" => "EGS",
                        "itemCode" => "EG-249628635-1",
                        "unitType" => "EA",
                        "quantity" => 35,
                        "unitPrice" => 247.96000,
                        "netSale" => 7810.74000,
                        "totalSale" => 8678.60000,
                        "total" => 8887.04360,
                        "commercialDiscountData" => [
                            [
                                "amount" => 867.86000,
                                "description" => "XYZ",
                                "rate" => 2.3
                            ]
                        ],
                        "itemDiscountData" => [
                            [
                                "amount" => 10,
                                "description" => "ABC",
                                "rate" => 2.3
                            ],
                            [
                                "amount" => 10,
                                "description" => "XYZ",
                                "rate" => 4.0
                            ],
                            [
                                "amount" => 11,
                                "description" => "SSS",
                                "rate" => 4.0
                            ]
                        ],
                        "valueDifference" => 20,
                        "taxableItems" => [
                            [
                                "taxType" => "T1",
                                "amount" => 1096.30360,
                                "subType" => "V009",
                                "rate" => 14
                            ]
                        ]
                    ]
                ],
                "totalSales" => 8678.60000,
                "totalCommercialDiscount" => 867.86000,
                "totalItemsDiscount" => 20,
                "extraReceiptDiscountData" => [
                    [
                        "amount" => 0,
                        "description" => "ABC",
                        "rate" => 10
                    ]
                ],
                "netAmount" => 7810.74000,
                "feesAmount" => 0,
                "totalAmount" => 8887.04360,
                "taxTotals" => [
                    [
                        "taxType" => "T1",
                        "amount" => 1096.30360
                    ]
                ],
                "paymentMethod" => "C",
                "adjustment" => 0,
                "contractor" => [
                    "name" => "contractor1",
                    "amount" => 2.563,
                    "rate" => 2.3
                ],
                "beneficiary" => [
                    "amount" => 20.569,
                    "rate" => 2.147
                ]
            ];
    
    
     function generateReceiptUUID(array $receipt): string {
        // Ensure UUID is empty before generation
        $receipt['header']['uuid'] = "";
    
        // Normalize the receipt object by serializing and flattening
        $normalizedString = normalizeReceipt($receipt);
    
        // Create SHA-256 hash
        $hash = hash('sha256', $normalizedString);
    
        return strtoupper($hash); // Convert to uppercase (if required)
    }
    
    function normalizeReceipt(array $receipt): string {
        // Sort keys to maintain consistency
        ksort($receipt);
    
        $normalizedString = "";
        foreach ($receipt as $key => $value) {
            if (is_array($value)) {
                // Recursive call for nested arrays
                $normalizedString .= strtoupper($key) . normalizeReceipt($value);
            } else {
                // Append key and value in normalized format
                $normalizedString .= strtoupper($key) . '"' . $value . '"';
            }
        }
    
        return $normalizedString;
    }
    
    $uuid = generateReceiptUUID($receiptData);
    
    $receiptData["header"]["uuid"] = $uuid;
    
    $formattedData = [
        "receipts" => [$receiptData] // تغليف البيانات داخل مصفوفة
    ];
    
    echo  $formattedData;
  

How to call vertex ai script from php from a browser url on a linux or Mac server?

I am trying to call a vertex ai generated python script to generate text from a php page and invoke it from a browser url.

The python script does not work on a linux or Mac server(but works on windows) when invoked from php through the browser url.

Interestingly the script works in terminal.

I am calling the vertex ai python script from php like this:

$Output = shell_exec(“python3 vertex.py”);

print($Output);

I am looking for a way to run the python script from the browser when called or invoked from the php script on a linux or macOS Server.

I am thinking that the issue could be due to/linked to handling virtual environment using php when the python script is invoked from the browser using php.

Bottom line it could be linked to the following underlying issues:

  1. How to handle google login/authentication for vertex scripts when called from the browser?

  2. It could also be linked to the handling of the virtual environment using php or python.