How to generate GraphQL Schema from schema.graphql file in PHP - php

I have created the schema.graphql file in PHP using the following code:
$data = SchemaPrinter::doPrint($schema);
file_put_contents('/var/cache/Graphql/schema.graphql', $data);
Now I want to create new schema using this file content. How to achieve this?

I have created the schema from schema.graphql using the BuildSchema::build().
By default, such schema is created without any resolvers. So we need to define our custom resolvers as follows:
$contents = file_get_contents($this->projectDir.'/config/schema.graphql');
$typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {
$name = $typeConfig['name'];
if ($name === 'Query') {
$typeConfig['resolveField'] =
function ($source, $args, $context, ResolveInfo $info) {
if ($info->fieldDefinition->name == 'login') {
if ($args['userName'] === 'test' && $args['password'] === '1234') {
return "Valid User.";
} else {
return "Invalid User";
}
} elseif ($info->fieldDefinition->name == 'validateUser') {
if ($args['age'] < 18) {
return ['userId' => $args['userId'], 'category' => 'Not eligible for voting'];
}
}
}
}
;
}
return $typeConfig;
};
$schema = BuildSchema::build($contents, $typeConfigDecorator);

Related

Use PHP function to override default JSON target with Array

We built an API to directly access other social networks APIs using our keys.
I'm trying to build a fuction to access that API.
The default function has been written and is working.
Question
How can I specify a new array to target the json data?
This will override the default setting.
function SocialAPI($handle, $service, $path="") {
$handle = strtolower($handle);
$service = strtolower($service);
$api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
if($api !== false) {
$data = json_decode($api, true);
if($data !== null) {
if($service === "twitter") {
return $data['0']['followers_count'];
}
if($service === "instagram") {
if(!empty($path)) {
while($id = array_shift($path)) {
echo $data[$id];
}
return $data;
} else {
return $data['user']['followed_by']['count'];
}
}
} else {
return false;
}
} else {
return "API call failed.";
}
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", "['user']['full_name']");
exit();
function array_deref($data, $keys) {
return empty($keys) ? $data
: array_deref($data[$keys[0]], array_slice($data, 1))
}
function SocialAPI($handle, $service, $path="") {
$handle = strtolower($handle);
$service = strtolower($service);
$api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
if ($api === false) {
return "API call failed.";
}
$data = json_decode($api, true);
if($data !== null) {
return false;
}
if ($service === "twitter") {
if (empty($path)) $path = ['0','followers_count'];
return array_deref($data, $path);
} elseif ($service === "instagram") {
if (empty($path)) $path = ['user','followed_by'];
return array_deref($data, $path);
}
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", ['user', 'full_name']);
echo SocialAPI("JohnDoe", "Instagram");
exit();
I added a utility function, array_deref, to walk the arrays recursively (calls itself to handle each level down).

PHP get link from txtfile, unset this link inside the array and get random array value

I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}

Codeigniter custom search function issue

Hello I am writing an php application and currently I'm stuck at a method that retrives flights from the database and applies diffrent filters to it. There are no problems when I initially load the page without any filters applied, all records from DB are loaded as expected. Then again everything as expected when I use "Departure Airport" or "Arrival Airport" filters along with "Bookable Only" filter.
It is whole of another story when you try to use "Bookable Only" filter on its own, it doesn't load any records from database. That's the same with "Aircraft" filter, doesn't work on its own and with "Bookable Only" filter but works when combined with both or either one of Airport filters + "Bookable Only" filter
Schedules_model.php
public function getFilteredSchedule($available, $departureICAO, $arrivalICAO, $specificAircraftId)
{
$this->db->select('*');
if($departureICAO != FALSE) {
$this->db->where('departureICAO', $departureICAO);
}
if($arrivalICAO != FALSE) {
$this->db->where('arrivalICAO', $arrivalICAO);
}
if($specificAircraftId != FALSE) {
$this->db->where('aircraftId', $specificAircraftId);
}
$schedules = $this->db->where('active', 1)
->order_by('id', 'asc')
->get('schedules')
->result_array();
$schedulesAvailable = array();
if($available === TRUE) {
echo 'work';
foreach($schedules as $key => $schedule) {
if($this->RebuildVA->mustBeAtDepartureAirport()) {
if($this->Aircrafts->isAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
if(!$this->RebuildVA->allowMultipleAircraftBookings()) {
if(!$this->Aircrafts->isBooked($schedule['aircraftId'])) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
if(!$this->RebuildVA->allowMultiplePilotBookings()) {
if(!$this->Pilots->hasBookedFlight($this->session->userdata('pilotId'))) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
}
} else {
$schedulesAvailable = $schedules;
}
return $schedulesAvailable;
}
schedules.php
public function search()
{
$this->data['pageTitle'] = 'Schedule Search';
$this->data['pageDisplayedTitle'] = 'Schedule Search';
$available = (bool) $this->input->post('available');
$this->data['schedules'] = $this->Schedules->getFilteredSchedule($available, $this->input->post('departureICAO'), $this->input->post('arrivalICAO'), $this->input->post('aircraftId'));
$airportsList = $this->Airports->getAllAirports(TRUE, TRUE); // Get set of all active airports
$aircraftsList = $this->Aircrafts->getAllAircrafts(TRUE, TRUE); // Get set of all active airports
// Prepare form inputs
$this->data['departureICAO'] = array(
'name' => 'departureICAO',
'id' => 'departureICAO',
'selected' => $this->input->post('departureICAO'),
'options' => $airportsList,
);
$this->data['arrivalICAO'] = array(
'name' => 'arrivalICAO',
'id' => 'arrivalICAO',
'selected' => $this->input->post('arrivalICAO'),
'options' => $airportsList,
);
$this->data['aircraftId'] = array(
'name' => 'aircraftId',
'id' => 'aircraftId',
'selected' => $this->input->post('aircraftId'),
'options' => $aircraftsList,
);
$this->data['available'] = array(
'name' => 'available',
'id' => 'available',
'checked' => set_checkbox('available', $this->input->post('available'), FALSE),
'value' => TRUE,
);
$this->load->view('schedules/scheduleSearch', $this->data);
}
I tried debugging everything and following the process step by step as well as trial and error method but none give expected effects. Any ideas?
By trial and error method I have found some kind of a work around that some how does the job. If anyone has any suggestions regarding it or how I could improve it, please feel free, as I am looking for performance in the app.
The required changes were in the Model:
public function getFilteredSchedule($available, $departureICAO, $arrivalICAO, $specificAircraftId)
{
$this->db->select('*');
if($departureICAO != FALSE) {
$this->db->where('departureICAO', $departureICAO);
}
if($arrivalICAO != FALSE) {
$this->db->where('arrivalICAO', $arrivalICAO);
}
if($specificAircraftId != FALSE) {
$this->db->where('aircraftId', $specificAircraftId);
}
$schedules = $this->db->where('active', 1)
->order_by('id', 'asc')
->get('schedules')
->result_array();
$schedulesAvailable = array();
// Check if any of the filters is required
if(!$this->RebuildVA->mustBeAtDepartureAirport() && $this->RebuildVA->allowMultipleAircraftBookings() && $this->RebuildVA->allowMultiplePilotBookings()) {
$schedulesAvailable = $schedules;
// Check if only bookable flights has been checked
} elseif($available === TRUE) {
foreach($schedules as $key => $schedule) {
// Allow multiple schedule bookings
// Check if the aircraft must be at departure airport
if($this->RebuildVA->mustBeAtDepartureAirport()) {
if($this->Aircrafts->isAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
// Check if use of other aircraft of same type is allowed
if($this->RebuildVA->allowOtherAircraftUse()) {
if($this->Aircrafts->aircraftTypeAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
unset($schedulesAvailable[$key]);
continue;
}
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
// Check if there is a limit of only one booking at time per aircraft
if(!$this->RebuildVA->allowMultipleAircraftBookings()) {
if(!$this->Aircrafts->isBooked($schedule['aircraftId'])) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
// Check if there is a limit of only one booking at time per pilot
if(!$this->RebuildVA->allowMultiplePilotBookings()) {
if(!$this->Pilots->hasBookedFlight($this->session->userdata('pilotId'))) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
}
} else {
$schedulesAvailable = $schedules;
}
return $schedulesAvailable;
}

like clause in codeigniter

I want to include like clause in the case of last_name.This is my controller code used for search box.I want to compare form value last_name with db value family_name.
public function filtered_volunteer_details()
{
$user_data = $this->session->userdata("logged_user");
$tab_result = array();
if (is_array($user_data) && $user_data["user_role"] == "staff")
{
if ($this->input->method() == "post")
{
$condition = array();
$data = $this->input->post();
if(isset($data["membership_number"]) && $data["membership_number"]!= "")
{
$condition["membership_number"]=trim($data["membership_number"]);
}
if(isset($data["last_name"]) && $data["last_name"]!= "")
{
$condition["family_name "]=trim($data["last_name"]);
}
$this->load->model(array(
"Users"));
$result = $this->Users->get_volunteers("*",$condition);
$volunteer_tbl_list=array();
foreach($result as $volunteer_results)
{
$volunteer_tbl_list[] = $this->load->view("staff/manage_volunteer/volunteer_list_tbl_row", $volunteer_results, TRUE);
}
echo json_encode(array(
"status" => "success",
"volunteer_tbl_list" => $volunteer_tbl_list));
return;
}
}
echo json_encode(array(
"error" => "true",
"msg" => "Invalid Access."));
return;
}
This is my model code
public function get_volunteers($fields = "*",$condition=array())
{
$condition["staff"]="N";
$this->db->select($fields);
$query = $this->db->get_where(self::$tbl_name, $condition);
//var_dump($this->db->last_query());
return( $query->result() );
}
Try adding a $this->db->like() to the query in get_volunteers(). documentation
public function get_volunteers($fields = "*",$condition=array())
{
$condition["staff"]="N";
$this->db->select($fields);
$this->db->like($condition);
$this->db->from(self::$tbl_name);
return( $query->result() );
}

To store session in database

In the below codeigniter code I have placed the controller and model. My aim is to store the session college name in the db. I tried but it is not entering the session college name into db.college_name is in blank.
Controller
function create() {
$j=1;
$createcustomer = $this->input->post('createcustomer');
if( $this->input->post('createcustomer') != false ) {
foreach($createcustomer as $row_id) {
//this is validation command to update on the screen
$this->form_validation->set_rules("exam_name_" . $row_id, "'Exam name'","required");
$this->form_validation->set_rules("month_". $row_id,"`Month`","required");
$this->form_validation->set_rules("year_". $row_id,"`Year`","required","required|");
}
}
if ($this->form_validation->run() == FALSE) {
$data["message"]="";
$this->load->view("exam_view",$data);
} else {
while($j<=$this->uri->segment(3)) {
$data = array(
'exam_name' => $this->input->post('exam_name_'.$j),
'month' => $this->input->post('month_'.$j),
'year' => $this->input->post('year_'.$j)
);
$exam_name=$this->input->post('exam_name_'.$j);
$data1 = $this->session->userdata("college_name");
if ($exam_name != "") {
$this->exam_model->add_record($data,$data1);
// $this->load->view("success_msg",$data);
}
$j++;
} //end of while condition
} //end of if condition
redirect('exam_site', 'refresh');
//$this->index();
}
Model:
function add_record($data,$data1) {
$this->db->insert('exam_table', $data,$data1);
//$this->db->insert('exam_table', $data1);
if ($this->db->_error_number() == 1062) {
$this->session->set_flashdata('duplicate', 'duplicate');
}
if ($this->db->_error_number() == "") {
$this->session->set_flashdata('create', 'create');
}
return;
}
change this:
$this->db->insert('exam_table', $data,$data1);
to this:
$this->db->insert('exam_table', $data);
$this->db->insert('exam_table', $data1);

Categories