iOS Background Location Tracking Not Working in Kill Mode(React Native)

I’m currently facing an issue with background location tracking in iOS.

On Android, both foreground and background (even in kill mode) tracking work perfectly.

However, on iOS, location tracking only works in the foreground and while minimized. When the app is completely closed (kill mode), it stops tracking.

I’m using the react-native-background-actions package, and it’s not functioning as expected on iOS in background/terminated mode.

Could you please guide me or suggest a solution to enable background or terminated (kill mode) location tracking on iOS?

How to render pages with hooks for Server Side Rendering in next.js

I am familiar with React and recently started next.js for SEO optimization.

My problem is that i do not understand how to make pages static

My layout.tsx:

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <Head />
      <body>
        <UserProvider>
          <PageOverlay />
          <PageOverlayError />
          <Navbar />
          <div className="layout">
            <Sidebar />
            {children}
          </div>
        </UserProvider>
      </body>
    </html>
  );
}

As here i have UserProvider which is global context, where i store logged in user data and display/use it in components. But here as my context uses hooks it becomes client side rendered?

"use client";

...

const UserContext = createContext<UserContextType | undefined>(undefined);

export const UserProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  ...

  return (
    <UserContext.Provider value={{
      user,
      setUser,
      loadingUI,
      errorUI,
      isSidebarOpen,
      toggleSidebar,
    }}>
      {children}
    </UserContext.Provider>
  );
};

export const useUser = (): UserContextType => {
  const context = useContext(UserContext);
  if (!context) {
    throw new Error("useUser must be used within a UserProvider");
  }
  return context;
};

So as i move DOM items (in this case it would be some page.tsx content) inside <UserProvider> it automtacially becomes client side rendered? and i cannot set metadata?
Is there a way to make it server side rendered with hooks or should i use other approach?

Insert script into HTML head section when in development and not in production

I want to insert the below script tag into my popup.html and options.html when compiled in dist folder:

<script src="http://localhost:8097"></script>

I need this to be the first script before any other scripts. Below is how I expect the script to look in my HTML:

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
 <script src="http://localhost:8097"></script>
 <script src="example.js"></script>
 <script src="react.js"></script>
</head>
<body>
  
</body>
</html>

How can I go about injecting this script for local development only, when working with Webpack?

Here’s my set-up so far:

webpack.dev.js:

const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    mode: 'development',
    devtool: 'cheap-module-source-map'
});

webpack.common.js:

const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    entry: {
        popup: path.resolve('src/popup/popup.tsx'),
        options: path.resolve('src/options/options.tsx'),
        background: path.resolve('src/background/background.ts'),
        contentScript: path.resolve('src/contentScript/contentScript.js')
    },
    module: {
        rules: [
            {
                use: 'ts-loader',
                test: /.tsx?$/,
                exclude: /node_modules/
            },
            {
                use: ['style-loader', 'css-loader'],
                test: /.css$/i
            },
            {
                type: 'asset/resource',
                test: /.(jpg|jpeg|png|woff|woff2|eot|ttf|svg)$/
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin({
            cleanStaleWebpackAssets: false
        }),
        new CopyPlugin({
            patterns: [
                {
                    from: path.resolve('src/static'),
                    to: path.resolve('dist/')
                }
            ]
        }),
        ...getHtmlPlugin(['popup', 'options'])
    ],
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: '[name].js',
        path: path.resolve('dist')
    },
    optimization: {
        splitChunks: {
            chunks: 'all'
        }
    }
};

function getHtmlPlugin(chunks) {
    return chunks.map(
        (chunk) =>
            new HtmlPlugin({
                title: 'Test',
                filename: `${chunk}.html`,
                chunks: [chunk]
            })
    );
}

I can’t seem to integrate my react three fiber (written jsx) with my nextjs project (written in tsx). Is there anyway to integrate them?

I created a NextJS typescript project using react 18 and I want to integrate a React Three Fiber 3D feature into it. But I keep getting

Error: Cannot read properties of undefined (reading 'ReactCurrentOwner')

I also cant upgrade to @react-three/fiber@alpha because I am on react 18 and apparently that needs react 19. Is there anyway to integrate the two together?

The code that is causing the error Overview.tsx

"use client";

import { DateRangePicker } from "@/components/ui/date-range-picker";
import { MAX_DATE_RANGE_DAYS } from "@/lib/constants";
import { UserSettings } from "@prisma/client";
import { differenceInDays, endOfMonth, startOfMonth } from "date-fns";
import React, { useState } from "react";
import { toast } from "sonner";
import StatsCards from "./StatsCards";
import CategoriesStats from "./CategoriesStats";
// import GameScene from "../../../components/GameScene";
import dynamic from "next/dynamic"; // <-- Import dynamic

const GameScene = dynamic(() => import("../../../components/GameScene"), {
  ssr: false,
});

function Overview({ userSettings }: { userSettings: UserSettings }) {
  const [dateRange, setDateRange] = useState<{ from: Date; to: Date }>({
    from: startOfMonth(new Date()),
    to: endOfMonth(new Date()),
  });
  return (
    <>
      <div className=" w-5/6 ">
        <div className="w-full px-4 flex flex-wrap items-end justify-between gap-2 py-6">
          <StatsCards
            userSettings={userSettings}
            from={dateRange.from}
            to={dateRange.to}
          />

          <div className="w-full h-150 bg-card rounded-2xl flex justify-center items-center">
            <h1>Game here</h1>
            <GameScene />
          </div>

          <h2 className="text-3xl font-bold flex flex-grow">Overview</h2>
          <div className="flex flex-grow items-center gap-3 justify-end ">
            <DateRangePicker
              initialDateFrom={dateRange.from}
              initialDateTo={dateRange.to}
              showCompare={false}
              onUpdate={(values) => {
                const { from, to } = values.range;

                if (!from || !to) return;
                if (differenceInDays(to, from) > MAX_DATE_RANGE_DAYS) {
                  toast.error(
                    `The selected date range is too big. Max allowed range is ${MAX_DATE_RANGE_DAYS}`
                  );
                  return;
                }
                setDateRange({ from, to });
              }}
            />
          </div>
        </div>
        <div className="w-full px-4 flex flex-wrap items-end justify-between gap-2 py-6 ">
          <CategoriesStats
            userSettings={userSettings}
            from={dateRange.from}
            to={dateRange.to}
          />
        </div>
      </div>
    </>
  );
}

export default Overview;

The react 3 fiber jsx component im trying to put in the overview page
GameScene.jsx

"use client";

import React, { useRef } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import * as THREE from "three"; // Type imports

function Box() {
  const ref = useRef < THREE.Mesh > null;

  useFrame(() => {
    if (ref.current) {
      ref.current.rotation.x += 0.01;
    }
  });

  return (
    <mesh ref={ref}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color="orange" />
    </mesh>
  );
}

function GameScene() {
  return (
    <Canvas>
      <ambientLight intensity={0.5} />
      <pointLight position={[10, 10, 10]} />
      <Box />
    </Canvas>
  );
}

export default GameScene;


What I’ve tried:

  1. changing my next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  /* config options here */
  transpilePackages: ["three"],
};

export default nextConfig;


  1. changing my tsconfig.json
{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./src/types"],
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts",
    "next-env.d.ts",
    "src/types/**/*.d.ts",
    "components/Scene.jsx"
  ],
  "exclude": ["node_modules"]
}


Error that i am getting

Error

I’m new to Java programming but I don’t know where to start developing applications. I accept suggestions [closed]

I was taking the java course for an online course but the practical examples do not guide me to how to start thinking about developing applications in Java. Please if you can help me with suggestions. Thank you.

I understood what each concept I was taught was about, but I don’t have a guide on where to start in developing an app.

“Express.js route /api/test returns 404 when called from Next.js frontend via Axios”

  1. Problem
    I have an Express server running on port 5002 with this test endpoint:

    app.get(‘/api/test’, (req, res) => {
    res.json({ message: “Backend is working!” });
    });

Visiting http://localhost:5002/ in a browser shows the correct welcome message.

But visiting http://localhost:5002/api/test directly in a browser, Postman, or curl returns:

Cannot GET /api/test   (404 Not Found)

From my Next.js frontend (port 3000), calling the same endpoint with Axios yields:

AxiosError: Network Error
ERR_CONNECTION_REFUSED
  1. Expected Behavior
    A GET request to /api/test should return:

    { “message”: “Backend is working!” }

and the frontend Axios call should log the response without error.

  1. What I’ve Tried

Enabled CORS in Express with app.use(cors());

Bound the server to all interfaces: app.listen(PORT, ‘0.0.0.0’, …)

Cleared browser cache (Ctrl+Shift+R) and restarted both servers

Tested endpoint directly with curl and Postman (still gets 404)

  1. Relevant Code Snippets

    // server.js (Express)
    import express from ‘express’;
    import cors from ‘cors’;

    const app = express();
    app.use(cors());
    app.use(express.json());

    // Test endpoint
    app.get(‘/api/test’, (req, res) => {
    res.json({ message: “Backend is working!” });
    });

    const PORT = process.env.PORT || 5002;
    app.listen(PORT, ‘0.0.0.0’, () =>
    console.log(Server listening on port ${PORT})
    );

    // services/testConnection.ts (Next.js)
    import axios from ‘axios’;

    export const testConnection = async () => {
    return axios.get(${process.env.NEXT_PUBLIC_API_URL}/api/test);
    };

    useEffect(() => {
    testConnection()
    .then(res => console.log(‘Success:’, res.data))
    .catch(err => console.error(‘Error:’, err));
    }, []);

. Error Logs

Frontend console:

Browser/Postman:

Cannot GET /api/test   (404 Not Found)
  1. Question
    Why does my /api/test endpoint return 404 when accessed directly, and why does my Next.js frontend get ERR_CONNECTION_REFUSED?

What is the correct order for defining routes, CORS settings, and server binding so that this endpoint responds successfully to both direct and Axios requests?

How to create a cricket score ticker like this and populate it with API data in a React app?

When I was watching a live sports broadcast (cricket) on TV, I noticed an overlay showing match details with beautiful graphics and animations. It really caught my eye, and I’d love to build something similar in my React application.

My question is: How can I design and implement this kind of graphic ticker in React and how is it possible to populate it dynamically using data fetched from an API??

enter image description here

This is my attempt

export const ScoreTicker = ({ match, inningsTabs, viewStats }) => {
  console.log('score ticker match details --->>>', {
    match,
    inningsTabs,
    viewStats,
  });

  const { team1, team2, status, type } = match;
  const { roomSize } = viewStats;

  const findCurrentInning = (inningsDetails) => {
    return inningsDetails.find(
      (inning) => inning.other_details?.inning_status === 'in progress'
    );
  };

  const findFirstInning = (inningsDetails) => {
    return inningsDetails.find((inning) => inning.innings === 1);
  };

  // New function to get all innings for a specific team
  const getTeamInnings = (inningsDetails, teamId) => {
    return inningsDetails.filter((inning) => inning.team?.id === teamId);
  };

  // New function to create combined score string
  const getCombinedScore = (innings) => {
    if (!innings || innings.length === 0) return '';

    return innings
      .map((inning) => {
        const wickets = inning.details?.wickets || 0;
        const runs = inning.details?.runs || 0;
        const overs = inning.details?.overs || 0;
        const balls = inning.details?.balls || 0;

        return `${runs}/${wickets} (${overs}.${balls})`;
      })
      .join(' & ');
  };

  const currentInning = findCurrentInning(inningsTabs);
  const firstInning = findFirstInning(inningsTabs);
  const inningThisOver = currentInning?.details?.thisOver;

  // Determine team IDs
  const teamOneId = firstInning?.team?.id || match?.team1?.id;
  const teamOne = teamOneId === match?.team1?.id ? match?.team1 : match?.team2;
  const teamTwo = teamOneId === match?.team1?.id ? match?.team2 : match?.team1;

  // Get all innings for each team
  const team1Innings = getTeamInnings(inningsTabs, teamOne.id);
  const team2Innings = getTeamInnings(inningsTabs, teamTwo.id);

  // Create combined score strings
  const team1CombinedScore = getCombinedScore(team1Innings);
  const team2CombinedScore = getCombinedScore(team2Innings);
  return (
    <motion.div
      initial={{ y: 100 }}
      animate={{ y: 0 }}
      transition={{ type: 'spring', damping: 20 }}
      className="fixed bottom-0 left-0 right-0 h-32 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 border-t border-white/10 shadow-2xl"
    >
      <div className="w-full max-w-xl mx-auto transform transition-all duration-300 pt-2">
        {/* Match Header */}
        <div className="flex justify-between items-start mb-4 animate-fadeIn">
          <div className="flex items-center justify-center">
            <div className="flex space-x-0.5">
              <p className="text-cyan-400 text-xxs">
                {roomSize ? roomSize : 0}
              </p>
              <MatchStatusTypeDetails status={status} type={type} />
            </div>

            {/* sponsor identity */}
            <img
              src={`/sponsors/livpuro.webp`}
              alt={`Livpuro`}
              className="w-20 h-5 rounded-full object-contain"
            />
          </div>

          <div className="text-right">
            {/* match date, championship name */}
            <div className="flex items-center justify-end gap-x-2 text-xxs text-gray-200 truncate max-w-[250px]">
              {match.date}
              {match.championship.id && (
                <div className="flex items-center justify-center gap-x-1">
                  <Separator
                    orientation={`vertical`}
                    className={`w-[2px] h-3 mt-[2px] mr-1 bg-yellow-400`}
                  />
                  {match.championship.name}
                </div>
              )}
            </div>

            {/* match venue and city */}
            <div
              className="text-xxs text-gray-200 gap-x-2"
              aria-label="Match location"
            >
              {match.place?.venue}{' '}
              {match.place?.venue && match.place?.city ? ', ' : ''}{' '}
              {match.place?.city ?? 'Unknown City'}
            </div>
          </div>
        </div>

        {/* Teams Section */}
        <div className="space-y-3">
          {[
            {
              team: teamOne.name,
              logo: teamOne.logo,
              score: team1CombinedScore || teamOne.score,
            },
            {
              team: teamTwo.name,
              logo: teamTwo.logo,
              score: team2CombinedScore || teamTwo.score,
            },
          ].map(({ team, logo, score }, index) => (
            <div
              key={index}
              className="flex items-center justify-between"
              style={{ animationDelay: `${index * 100}ms` }}
            >
              <div className="flex items-center space-x-3">
                <div>
                  <img
                    src={logo.light} // Default logo for light mode
                    alt={`${team} logo`}
                    className="w-8 h-8 rounded-full object-cover dark:hidden"
                  />
                  <img
                    src={logo.dark} // Logo for dark mode
                    alt={`${team} logo`}
                    className="w-8 h-8 rounded-full object-cover hidden dark:block"
                  />
                </div>

                <span className="font-bold text-lg md:text-xl text-cyan-100">
                  {team}
                </span>
              </div>
              <span className="font-bold text-lg md:text-2xl text-cyan-100">
                {score} xx
              </span>
            </div>
          ))}
        </div>
      </div>
    </motion.div>
  );
};

it’s producing very simple design. I want something special effect like on live telecast

Securing APIs Against Unauthorized Access

We have four React Vite-based websites:

https://www.production.demo.com

https://www.production.googleteam.demo.com

https://www.production.items.demo.com

https://www.production.card.demo.com

All of these websites use a single Node.js backend.

We have implemented some basic security features such as CORS origin restrictions. However, these measures are currently not sufficient, as we’ve noticed that some users are able to access our APIs using tools like Postman or other HTTP clients by bypassing the origin check.

We’re looking for suggestions on how to further secure our APIs and prevent unauthorized access

Does onBlur see the latest state updated in onChange in React?

I’m using a React input element that has both onChange and onBlur handlers. In the onChange, I’m updating a state. Then, in onBlur, I need to use the updated value of that state.

I want to make sure the onBlur handler sees the most recent state that was set during onChange.
In my case it is working fine. But just wondering is it always guaranteed to work?

Because setState is async and the onBlur event might run before setState has run and component has rerendered?

import React, { useState } from 'react';

function MyComponent() {
  const [stateVal, setStateVal] = useState("");

  const handleChange = (e) => {
    // Update a separate piece of state
    setStateVal('random');
  };

  const handleBlur = () => {
    console.log("onBlur - stateVal:", stateVal);
    // Will this reflect the latest state set in handleChange?
  };

  return (
    <input
      onChange={handleChange}
      onBlur={handleBlur}
    />
  );
}

Penjelasan Proyek: Aplikasi Manajemen Tugas “TaskMate”

Penjelasan Proyek: Aplikasi Manajemen Tugas “TaskMate”

TaskMate adalah sebuah aplikasi manajemen tugas berbasis web yang dirancang untuk membantu pengguna dalam mengatur, memprioritaskan, dan menyelesaikan pekerjaan mereka secara lebih efisien. Proyek ini bertujuan untuk menciptakan solusi produktivitas yang sederhana namun powerful, khususnya untuk pelajar, pekerja lepas, dan tim kecil yang memerlukan alat pengelolaan tugas yang praktis.

Fitur utama TaskMate meliputi pembuatan daftar tugas, penjadwalan deadline, penetapan prioritas, serta notifikasi otomatis untuk pengingat tugas. Pengguna juga dapat membagi tugas ke dalam kategori dan menggunakan label warna untuk membedakan jenis pekerjaan. Selain itu, aplikasi ini mendukung kolaborasi tim, di mana beberapa pengguna dapat berbagi proyek, membagi tanggung jawab, serta memantau perkembangan tugas secara real-time.

Proyek ini dikembangkan menggunakan teknologi modern seperti ReactJS untuk antarmuka pengguna dan Firebase sebagai backend untuk penyimpanan data dan autentikasi. Desain UI/UX dirancang agar ramah pengguna, responsif di berbagai perangkat, dan mudah digunakan bahkan bagi pemula sekalipun.

Melalui TaskMate, kami berharap pengguna dapat meningkatkan produktivitas dan mengelola waktu mereka dengan lebih baik. Aplikasi ini juga dapat menjadi alternatif dari aplikasi sejenis yang sering kali terlalu kompleks atau berbayar. Proyek ini masih dalam tahap pengembangan dan terbuka untuk masukan pengguna guna penyempurnaan lebih lanjut.

How can I wait for a promise to resolve in synchronous code?

This is a simple question that, it seems, no one wants to answer. If the answer is out there, I could not find it because it is submerged under a sea of redirections and substitutions. I ask for a straight answer, not a redirection or a substitution.

Say I have a promise, and I want to synchronously wait until it is resolved. How can I do this?

Formally, I am looking for a function such as the following:

function wait_for_promise <return_type> (promise: Promise <return_type>): return_type { ? }

— Here, the question mark needs to be replaced with a solution. This function must return insofar as the promise is ever resolved.

Let me state clearly what I am not asking about.

  • I am not asking about how to execute code after the promise resolves — I am asking about how to wait for a promise to resolve in synchronous code.
  • I am not asking bout how to use the async await notation — I am asking about how to wait for a promise to resolve in synchronous code.
  • I am not asking about how to use the then method to chain promises — I am asking about how to wait for a promise to resolve in synchronous code.
  • I am not asking about how the JavaScript event loop works — I am asking about how to wait for a promise to resolve in synchronous code.

If this is impossible, then please answer «this is impossible». If you can explain why, please do so.

fix the ranking issue [closed]

This is my code where I am getting country ranking on corruption by get request

public function getByYear($year)
    {
        return $this->safeCall(function () use ($year) {
            $rankings = CorruptionRanking::where('year', $year)
                ->orderBy('points', 'desc')
                ->get();

            if ($rankings->isEmpty()) {
                return $this->errorResponse('No data found for the given year', 404);
            }
            $rank = 1;
            $rankings->each(function ($ranking, $index) use (&$rank, $rankings) {
                if ($index > 0 && $ranking->points === $rankings[$index - 1]->points) {
                    $ranking->rank = $rank -1;
                } else {
                    $ranking->rank = $rank;
                    $rank++;
                }
                $ranking->save();
            });
            return $this->successResponse('Rankings retrieved successfully', [
                'year' => $year,
                'rankings' => $rankings
            ]);
        });
    }

And this is my output

"rankings": [
            {
                "id": 1541,
                "country_name": "Denmark",
                "year": 2017,
                "points": 8.8,
                "rank": 1,
                "created_at": "2025-04-17T11:41:36.000000Z",
                "updated_at": "2025-04-19T05:37:40.000000Z"
            },
            {
                "id": 1886,
                "country_name": "Finland",
                "year": 2017,
                "points": 8.5,
                "rank": 2,
                "created_at": "2025-04-17T11:41:36.000000Z",
                "updated_at": "2025-04-19T05:38:37.000000Z"
            },
            {
                "id": 3680,
                "country_name": "Norway",
                "year": 2017,
                "points": 8.5,
                "rank": 2,
                "created_at": "2025-04-17T11:41:38.000000Z",
                "updated_at": "2025-04-19T05:38:37.000000Z"
            },
            {
                "id": 4715,
                "country_name": "Switzerland",
                "year": 2017,
                "points": 8.5,
                "rank": 2,
                "created_at": "2025-04-17T11:41:39.000000Z",
                "updated_at": "2025-04-19T05:38:37.000000Z"
            },
            {
                "id": 4370,
                "country_name": "Singapore",
                "year": 2017,
                "points": 8.4,
                "rank": 3,
                "created_at": "2025-04-17T11:41:39.000000Z",
                "updated_at": "2025-04-19T05:38:37.000000Z"
            },

But i am expecting output where Denmark rank 1 its good and Finland,Norway,Switzerland rank 2 is also good But Singapore,Sweden should be rank 5 and this will follow the ranking sequence thanks

How to spl_autoload_register multiple directories for same namespace

I have an existing autoload, which goes through json file to autoload different 3rd party files, this works really well. However there are new files being added to project and they are in different directories but using the same namespace. Issue is that it seems only to load the last directory for the same namespace, so when it goes to load the file it can’t find it.

I figured that would need to put the directories into an array and loop through that, but I am unsure how to go about that in PHP code.

Current PHP Code

spl_autoload_register(function (string $class_name): void {
    // Get mappings from json
    $conductor = file_get_contents(__DIR__.'/autoload.json');
    $conductor = str_replace('\', '\\', $conductor);
    $configuration = json_decode(stripslashes($conductor), true);

    // Map the namespace to the corresponding folder
    $namespace_mapping = $configuration['autoload']['psr-4'];
 
    foreach ($namespace_mapping as $namespace => $directory) {
        if (
            strpos($class_name, $namespace = trim($namespace, '\')) !== 0
            || (!$directory = realpath(__DIR__ . DIRECTORY_SEPARATOR . trim($directory, DIRECTORY_SEPARATOR)))
        ) {
            continue; // Class name doesn't match or the directory doesn't exist
        }
 
        // Require the file
        $class_file = $directory . str_replace([$namespace, '\'], ['', DIRECTORY_SEPARATOR], $class_name) . '.php';
        if (file_exists($class_file)) {
            require_once $class_file;
        }
    }
});

Current Json

{
    "autoload": {
        "psr-4": {
            "Psr\Log\": "psr/log/src/",
            "Psr\Http\Server\": "psr/http-server-handler/src/",
            "Psr\Http\Server\": "psr/http-server-middleware/src/",
            "Psr\Http\Message\": "psr/http-message/src/",
            "Psr\Http\Message\": "psr/http-factory/src/",
            "Psr\Container\": "psr/container/src/"
        }
    }
}

I was thinking needing to do something like this in json:

"Psr\Http\Server\": ["psr/http-server-handler/src/", "psr/http-server-middleware/src/"],

Any assistance would be greatly appreciated.

AI Blog Title Generator [closed]

Below there is part of the code for AI blog title generator in wordpress I found online. This is causing an error and I suspect this is due to the variable $jsonData which has not been initialized and is being passed as an empty string. Anyone can grab the entire html and code snippet from https://www.youtube.com/watch?v=Pl25QeHVjvM&t=417s

function jsonToModel($modelClass, $jsonData) {
try {
    return $modelClass($jsonData);
} catch (Exception $e) {
    echo "Validation error: " . $e->getMessage();
    return null;
}
}
function validateJsonWithModel($modelClass, $jsonData) {
$validatedData = [];
$validationErrors = [];

if (is_array($jsonData)) {
    foreach ($jsonData as $item) {
        try {
            $modelInstance = $modelClass($item);
            array_push($validatedData, $modelInstance);
        } catch (Exception $e) {
            array_push($validationErrors, ["error" => $e->getMessage(), "data" => $item]);
        }
    }
} elseif (is_assoc($jsonData)) {
    try {
        $modelInstance = $modelClass($jsonData);
        array_push($validatedData, $modelInstance);
    } catch (Exception $e) {
        array_push($validationErrors, ["error" => $e->getMessage(), "data" => $jsonData]);
    }
} else {
    throw new ValueError("Invalid JSON data type. Expected associative array or array.");
}
return [$validatedData, $validationErrors];

}