0

I have a problem with my code, when a User have all "stations" the code work but if he dont have one i have the (undefined offset *) error,

my code look like that ( in my controller )

public function index()
{
    $entityManager = $this->getDoctrine()->getManager();
    $stations = $this->getListOfStations();
    $stationsJson = [];

    $events = $entityManager->getRepository('App:User')
        ->getEventInRealTime($this->getUser());

    foreach ($stations as $station) {
        $stationsJson[] = [
            'typeEvents' => $events[$station->getId()],
        ];
    }

    return new JsonResponse(array('stations' => $stationsJson));
}


private function getListOfStations()
{
    /** @var UserInterface $user */
    $user = $this->getUser();
    $entityManager = $this->getDoctrine()->getManager();

    if (!$this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
        $stations = $user->getStations();
    } else {
        $stations = $entityManager->getRepository('App:Station')->findAll();
    }

    return $stations;
}

and my repository

public function getEventInRealTime($user)
{
    $qb = $this->createQueryBuilder('u');
    $events = $qb
        ->select('s.id as stationId, COUNT(e) as number, e.label as type')
        ->innerJoin('u.stations', 's')
        ->innerJoin('s.events', 'e')
        ->where('u = :user')
        ->setParameter('user', $user)
        ->andWhere('DAY(e.currentTime) =:day')
        ->setParameter('day', date('d'))
        ->andWhere('MONTH(e.currentTime) =:month')
        ->setParameter('month', date('m'))
        ->andWhere('YEAR(e.currentTime) =:year')
        ->setParameter('year', date('Y'))
        ->groupBy('s.id, type');

    $data = $events->getQuery()->getArrayResult();

    $result = [];

    foreach ($data as $row) {
        $result[$row['stationId']][] =
            [
                'number' => $row['number'],
                'type' => $row['type']
            ];
    }

    return $result;
}

i think its a problem its like, he dont find the "stations" when i do a findAll(), but i dont know how to fix it, when the user is super_admin he can have see all the stations but if is not super admin he can see only his stations

Imrickjames
  • 129
  • 9
  • 1
    Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – LF00 Nov 05 '19 at 01:10
  • May be you should check output of $stations = $this->getListOfStations(); and $events = $entityManager->getRepository('App:User') ->getEventInRealTime($this->getUser()); for both type of users. You can get better idea. – Tejas Gosai Nov 05 '19 at 05:24
  • i suggest you to check data in your array https://stackoverflow.com/questions/15310261/php-checking-if-array-index-exist-or-is-null – popota Nov 05 '19 at 09:22

0 Answers0