$id > 0)); if (!$ids) { return []; } $rows = DB::select( 'select distinct user_id from user_roles where role_id in (???)', array_map('strval', $ids) ); if (!is_array($rows)) { return []; } $userIds = []; foreach ($rows as $row) { $data = $row['user_roles'] ?? $row; if (!is_array($data) || !isset($data['user_id'])) { continue; } $userIds[] = (int) $data['user_id']; } return array_values(array_unique(array_filter($userIds, static fn ($id) => $id > 0))); } public function countUsersByRoleIds(array $roleIds): array { return $this->countByRoleIds($roleIds, false); } public function countActiveUsersByRoleIds(array $roleIds): array { return $this->countByRoleIds($roleIds, true); } private function countByRoleIds(array $roleIds, bool $activeOnly): array { $roleIds = array_values(array_unique(array_map('intval', $roleIds))); $roleIds = array_values(array_filter($roleIds, static fn ($id) => $id > 0)); if (!$roleIds) { return []; } $placeholders = implode(',', array_fill(0, count($roleIds), '?')); $joinUsersSql = $activeOnly ? ' join users u on u.id = ur.user_id and u.active = 1' : ''; $rows = DB::select( 'select ur.role_id, count(distinct ur.user_id) as user_count from user_roles ur' . $joinUsersSql . ' where ur.role_id in (' . $placeholders . ') group by ur.role_id', ...array_map('strval', $roleIds) ); if (!is_array($rows)) { return []; } $result = []; foreach ($rows as $row) { $roleId = $this->extractIntField($row, 'role_id'); if ($roleId <= 0) { continue; } $result[$roleId] = $this->extractIntField($row, 'user_count'); } return $result; } private function extractIntField(array $row, string $field): int { foreach ($row as $value) { if (!is_array($value)) { continue; } if (array_key_exists($field, $value)) { return (int) $value[$field]; } } if (array_key_exists($field, $row)) { return (int) $row[$field]; } return 0; } }