public function action_add_blocked($block = null) { if (empty($block) === true) { $block = $_POST['blocked']; } else { $block = str_replace('-', '.', $block); } $blacklist_item = Model_Blacklist::query()->where('expression', $block)->get_one(); if (empty($blacklist_item) === true) { $blacklist_item = Model_Blacklist::forge(array('expression' => $block)); $blacklist_item->save(); if (Input::is_ajax() === true) { echo $blacklist_item->id; } } else { if (Input::is_ajax() === true) { print_r(Format::forge(array('error' => 'Already Exists'))->to_json()); } else { Session::set('error', $block . ' is already in the blacklist!'); } } if (Input::is_ajax() === true) { die; } Response::Redirect_Back(); }
/** * Test for Format::forge($foo)->_from_xml() * * @test */ public function test__from_xml() { $xml = '<?xml version="1.0" encoding="UTF-8"?> <phpunit colors="true" stopOnFailure="false" bootstrap="bootstrap_phpunit.php"> <php> <server name="doc_root" value="../../"/> <server name="app_path" value="fuel/app"/> <server name="core_path" value="fuel/core"/> <server name="package_path" value="fuel/packages"/> </php> <testsuites> <testsuite name="core"> <directory suffix=".php">../core/tests</directory> </testsuite> <testsuite name="packages"> <directory suffix=".php">../packages/*/tests</directory> </testsuite> <testsuite name="app"> <directory suffix=".php">../app/tests</directory> </testsuite> </testsuites> </phpunit>'; $expected = array('@attributes' => array('colors' => 'true', 'stopOnFailure' => 'false', 'bootstrap' => 'bootstrap_phpunit.php'), 'php' => array('server' => array(0 => array('@attributes' => array('name' => 'doc_root', 'value' => '../../')), 1 => array('@attributes' => array('name' => 'app_path', 'value' => 'fuel/app')), 2 => array('@attributes' => array('name' => 'core_path', 'value' => 'fuel/core')), 3 => array('@attributes' => array('name' => 'package_path', 'value' => 'fuel/packages')))), 'testsuites' => array('testsuite' => array(0 => array('@attributes' => array('name' => 'core'), 'directory' => '../core/tests'), 1 => array('@attributes' => array('name' => 'packages'), 'directory' => '../packages/*/tests'), 2 => array('@attributes' => array('name' => 'app'), 'directory' => '../app/tests')))); $this->assertEquals(Format::forge($expected)->to_php(), Format::forge($xml, 'xml')->to_php()); }
public function get_user_info(Consumer $consumer, Token $token) { // Create a new GET request with the required parameters $url = 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,member-url-resources,picture-url,location,public-profile-url)'; $request = Request::forge('resource', 'GET', $url, array( 'oauth_consumer_key' => $consumer->key, 'oauth_token' => $token->access_token, )); // Sign the request using the consumer and token $request->sign($this->signature, $consumer, $token); $user = \Format::forge($request->execute(), 'xml')->to_array(); // Create a response from the request return array( 'uid' => $user['id'], 'name' => $user['first-name'].' '.$user['last-name'], 'nickname' => end(explode('/', $user['public-profile-url'])), 'description' => $user['headline'], 'location' => \Arr::get($user, 'location.name'), 'urls' => array( 'Linked In' => $user['public-profile-url'], ), ); }
public function action_models($id = '') { // set the default view $view = 'model'; switch ($id) { case 'access': $title = 'Access'; $model = Format::forge(file_get_contents(APPPATH . 'assets/nova2/models/access.yaml'), 'yaml')->to_array(); break; case 'docking': $title = 'Docking'; $model = Format::forge(file_get_contents(APPPATH . 'assets/nova2/models/docking.yaml'), 'yaml')->to_array(); break; case 'system': $title = 'System'; $model = Format::forge(file_get_contents(APPPATH . 'assets/nova2/models/system.yaml'), 'yaml')->to_array(); break; case 'tour': $title = 'Tour'; $model = Format::forge(file_get_contents(APPPATH . 'assets/nova2/models/tour.yaml'), 'yaml')->to_array(); break; case 'users': $title = 'Users'; $model = Format::forge(file_get_contents(APPPATH . 'assets/nova2/models/users.yaml'), 'yaml')->to_array(); break; case 'wiki': $title = 'Wiki'; $model = Format::forge(file_get_contents(APPPATH . 'assets/nova2/models/wiki.yaml'), 'yaml')->to_array(); break; default: $item = $id; if (empty($item)) { $item = 'index'; } switch ($item) { case 'privmsgs': $title = 'Private Messages'; break; case 'personallogs': $title = 'Personal Logs'; break; case 'depts': $title = 'Departments'; break; default: $title = ucfirst($item); break; } $model = false; $view = 'model_' . $item; break; } $this->_view = 'components/nova2/developers/core/' . $view; $this->_data->header = $title; $this->_data->model = $model; $this->template->title .= $title . ' Model'; }
public static function createReferral($data = array()) { if (count($data) <= 0) { return; } $referralID = array(); $referralID = \DB::query("INSERT INTO\n " . static::$tblReferrals . "\n ( id\n ,user_id\n ,introducer_id\n ,introducer_agent_name\n ,company_id\n ,product_id\n ,dialler_lead_id\n ,dialler_list_id\n ,dialler_list_name\n ,referral_date\n ,disposition_id\n ,title\n ,forename\n ,surname\n ,street_and_number\n ,area\n ,district\n ,town\n ,county\n ,country_id\n ,post_code\n ,date_of_birth\n ,tel_home\n ,tel_work\n ,tel_mobile\n ,email\n ,notes\n ,consolidation_centre )\n VALUES\n ( NULL\n ," . (isset($data['user_id']) ? (int) $data['user_id'] : 0) . "\n ," . (isset($data['introducer_id']) ? (int) $data['introducer_id'] : 0) . "\n ,'" . (isset($data['introducer_agent_name']) ? $data['introducer_agent_name'] : false) . "'\n ," . (isset($data['company_id']) ? (int) $data['company_id'] : 0) . "\n ," . (isset($data['product_id']) ? (int) $data['product_id'] : 0) . "\n ," . (isset($data['dialler_lead_id']) ? (int) $data['dialler_lead_id'] : 0) . "\n ," . (isset($data['dialler_list_id']) ? (int) $data['dialler_list_id'] : 0) . "\n ,'" . (isset($data['dialler_list_name']) ? $data['dialler_list_name'] : '') . "'\n ,NOW()\n ," . (int) $data['disposition_id'] . "\n ,'" . (isset($data['title']) ? $data['title'] : false) . "'\n ," . (isset($data['forename']) ? \DB::quote($data['forename']) : "''") . "\n ," . (isset($data['surname']) ? \DB::quote($data['surname']) : "''") . "\n ," . (isset($data['street_and_number']) ? \DB::quote($data['street_and_number']) : "''") . "\n ," . (isset($data['area']) ? \DB::quote($data['area']) : "''") . "\n ," . (isset($data['district']) ? \DB::quote($data['district']) : "''") . "\n ," . (isset($data['town']) ? \DB::quote($data['town']) : "''") . "\n ," . (isset($data['county']) ? \DB::quote($data['county']) : "''") . "\n ," . (isset($data['country_id']) ? (int) $data['country_id'] : 0) . "\n ," . (isset($data['post_code']) ? \DB::quote($data['post_code']) : "''") . "\n ,'" . (isset($data['date_of_birth']) ? $data['date_of_birth'] : 'NULL') . "'\n ," . ((int) isset($data['tel_home']) && $data['tel_home'] > 0 ? $data['tel_home'] : 0) . "\n ," . ((int) isset($data['tel_work']) && $data['tel_work'] > 0 ? $data['tel_work'] : 0) . "\n ," . ((int) isset($data['tel_mobile']) && $data['tel_mobile'] ? $data['tel_mobile'] : 0) . "\n ," . (isset($data['email']) ? \DB::quote($data['email']) : "''") . "\n ," . (isset($data['notes']) ? \DB::quote($data['notes']) : "''") . "\n ," . (isset($data['consolidation_centre']) ? (int) $data['consolidation_centre'] : 0) . ")\n ", \DB::insert())->execute(); \Log::write('Dispo', \Format::forge($referralID)->to_json(), 'Referrals_model::createReferral()'); \Log::write('Dispo', 'Referral created with the ID of ' . $referralID[0], 'Referrals_model::createReferral()'); return $referralID[0]; }
public function response() { if ($this instanceof HttpBadRequestException) { $this->message = 'Missing or Invalid Parameter(s): ' . $this->getMessage(); } $response = null; if ($this->getMessage()) { $data = array('message' => $this->getMessage()); $response = \Format::forge($data)->to_json(); } return new \Response($response, $this->getCode()); }
/** * manage and execute queues * */ public function run() { // check pids if (\Config::get('queue.queue_parallel_number') <= count(glob(\APPPATH . 'tmp/' . \Config::get('queue.queue_pid_prefix') . '_*.pid'))) { \Log::debug('queue limit over.'); return; } $this->__process_file_name = \Config::get('queue.queue_pid_prefix') . '_' . getmypid() . '.pid'; // create pid file \File::create(\APPPATH . 'tmp', $this->__process_file_name); try { // check dead queues $recover = \Model_TaskQueue::recover_zombie_queues(); if (!empty($recover)) { \Model_TaskQueue::notify('zombie task recovered. ids = ' . implode(',', $recover)); } // check queues $queue = \Model_TaskQueue::pickup(); if (empty($queue)) { return; } // exec queue call_user_func_array('\\' . $queue['method'], \Format::forge($queue['options'], 'json')->to_array()); // finish (update to success) queue \Model_TaskQueue::finish($queue['id'], \Model_TaskQueue::STATUS_SUCCESS); } catch (\Exception $e) { if (\DB::in_transaction()) { \DB::rollback_transaction(); } if (isset($queue) and !empty($queue)) { // finish (update to error) queue \Model_TaskQueue::finish($queue['id'], \Model_TaskQueue::STATUS_ERROR); // send to notify method $body = array(); $body[] = 'task queue error occured.'; $body[] = '--------------------------------'; $body[] = 'id: ' . $queue['id']; $body[] = 'method: ' . $queue['method']; $body[] = 'options: ' . $queue['options']; if (is_array($e->getMessage())) { $body[] = 'reason: ' . implode(' ', $e->getMessage()); } elseif (!empty($e->getMessage())) { $body[] = 'reason: ' . $e->getMessage(); } \Model_TaskQueue::notify($body); } } finally { \File::delete(\APPPATH . 'tmp/' . $this->__process_file_name); } }
/** * Returns a list of event agenda items. * The method is mainly intended to be called using ajax * in this case, a json-formated string is returned. * @param int $event_id */ public function action_index($event_id = null) { !isset($event_id) and Response::redirect("event"); $event = Model_Orm_Event::find($event_id, array("related" => array("agendas"))); !isset($event) and Response::redirect("event"); if (Input::is_ajax()) { $response = Response::forge(Format::forge()->to_json($event->agendas)); $response->set_header("Content-Type", "application/json"); return $response; } else { $data['event'] = $event; $this->template->title = "Agenda items: " . $event->title; $this->template->content = View::forge('agenda/index', $data); } }
public function action_create() { //assumption: this will only be called using ajax if (!Input::is_ajax()) { return Response::forge("Access forbidden, only AJAX calls allowed", 403); } if (!Auth::has_access("location.create")) { return Response::forge("Only admins allowed here", 403); } if (Input::post("location_title", null) != null) { $loc = Model_Orm_Location::forge(); $loc->title = Input::post("location_title"); $loc->save(); $ret = array("id" => $loc->id); return Response::forge(Format::forge()->to_json($ret), 200, array("Content-Type" => "application/json")); } }
public function get_validate($apiKey = null) { $apiCheck = \Crm\Portal\Portal_Check::api_key($apiKey); if ($apiCheck === false) { $this->response(array('status' => 'FAIL', 'message' => 'Invalid API Key has been used, please contact your IT support!')); } else { $allFields = TRUE; $missingFields = array(); $surveyChoice = $apiCheck->survey; $surveyQuestions = \Model_Survey_Question::query()->where('survey_id', $surveyChoice)->where('required', '1')->get(); $allSurveyQuestions = \Model_Survey_Question::query()->where('survey_id', $surveyChoice)->get(); foreach ($surveyQuestions as $surveyRequired) { $requiredFields[] = 'form-q' . $surveyRequired->id; } foreach ($allSurveyQuestions as $surveyQuestions) { $questionFields[] = 'form-q' . $surveyQuestions->id; } // Check and make a list of any missing fields foreach ($requiredFields as $field) { if (is_null(Input::get($field, null)) || strlen(Input::get($field, null)) < 1 && !is_integer(Input::get($field, null)) || Input::get($field, null) == "-- Select") { $allFields = FALSE; $missingFields[] = $field; } } // If we have everything we need then we do our logic if ($allFields) { // Get the client type from the given questions $questionPassOn = array(); foreach ($questionFields as $singleQuestion) { $questionPassOn[$singleQuestion] = Input::get($singleQuestion, null); $questionPassOn[str_replace('form-q', 'form-e', $singleQuestion)] = Input::get(str_replace('form-q', 'form-e', $singleQuestion), null); } \log::write('PPI-DEBUG', \Format::forge($_GET)->to_json()); $clientType = \Crm\Portal\Portal_Check::choice($questionPassOn, $_GET, $apiKey); // If we can decide on a client type if (!is_null($clientType)) { $this->response(array('client_type' => $clientType)); } else { $this->response(array('status' => 'FAIL', 'message' => 'No client type could be decided. Please complete ALL the given questions.')); } } else { $this->response(array('status' => 'FAIL', 'code' => '101', 'message' => 'Not all required fields were submitted! Missing fields are ' . implode(", ", $missingFields), 'missing_fields' => $missingFields)); } } }
public static function load($table, $file) { $fixt_name = $file . '_fixt'; $file_name = $fixt_name . '.' . static::$file_ext; $fixt_file = APPPATH . 'tests/fixture/' . $file_name; if (!file_exists($fixt_file)) { exit('No such file: ' . $fixt_file . PHP_EOL); } // フィクスチャファイルを読み込んで配列に変換 $data = file_get_contents($fixt_file); $data = Format::forge($data, static::$file_type)->to_array(); // テーブルのデータを削除 static::empty_table($table); // フィクスチャデータの挿入 foreach ($data as $row) { list($insert_id, $rows_affected) = DB::insert($table)->set($row)->execute(); } Log::info('Table Fixture ' . $file_name . ' -> ' . $fixt_name . ' loaded', __METHOD__); return $data; }
function test_to_array_empty() { $array = null; $expected = array(); $this->assertEquals($expected, Format::forge($array)->to_array()); }
/** * Creates the Response and optionally attempts to auto-format the output * * @param string $body * @param int $status * @param string $mime * @param array $headers * @return Response */ public function set_response($body, $status, $mime = null, $headers = array()) { if ($this->auto_format and array_key_exists($mime, static::$auto_detect_formats)) { $body = \Format::forge($body, static::$auto_detect_formats[$mime])->to_array(); } $this->response = \Response::forge($body, $status, $headers); return $this->response; }
/** * Test for Format::forge($foo)->to_xml(null, null, 'xml', true) * * @test */ public function test_to_xml_cdata() { $array = array('articles' => array(array('title' => 'test', 'author' => '<h1>hero</h1>'))); $expected = '<?xml version="1.0" encoding="utf-8"?> <xml><articles><article><title>test</title><author><![CDATA[<h1>hero</h1>]]></author></article></articles></xml> '; $this->assertEquals($expected, Format::forge($array)->to_xml(null, null, 'xml', true)); }
/** * CSV出力 * * @access public * @param * @return void * @author kobayashi * @author ida */ protected function response_csv($data, $fleamarket_name) { $csv = mb_convert_encoding(Format::forge($data)->to_csv(), 'SJIS-win', 'UTF-8'); $file_name = $fleamarket_name . '_エントリ一覧.csv'; $response = new Response($csv, 200, array('Content-Type' => 'application/csv', 'Content-Disposition' => 'attachment; filename="' . $file_name . '"')); return $response; }
protected function fetch_rules() { // set rules array $rules = array(); // get permissions file config options $permission_file = Config::get('sentry.permissions.file'); // load global rules $rules = Config::get('sentry.permissions.rules'); // see if we should use config files or not if ($permission_file['name'] == 'config' or empty($permission_file['name']) or $permission_file['name'] == null) { // load current module specific rules if a module is active if (isset(\Request::active()->module)) { \Config::load(\Request::active()->module, true); $module_permissions = Config::get(\Request::active()->module . '.rules'); if (!empty($module_permissions)) { $rules = Arr::merge($rules, $module_permissions); } } return $rules; } // loop through module paths and see if listed file exists $file = false; foreach (Config::get('module_paths') as $path) { $path = $path . \Request::active()->module . DS; if (!empty($permission_file['path'])) { $path .= $permission_file['path'] . DS . $permission_file['name']; } else { $path .= $permission_file['name']; } if (file_exists($path)) { $file = $path; break; } } // if the file exists pull in rules if they are set if ($file) { // get file type switch ($permission_file['type']) { case 'ini': $info = parse_ini_file($file, true); break; case 'json': $info = json_decode(file_get_contents($file), true); break; case 'yaml': $info = \Format::forge(file_get_contents($file), 'yaml')->to_array(); break; case 'php': $info = (include $file); break; default: // move this somewhere else for easier debugging? throw new \SentryUserException(sprintf('Invalid permission file type "%s".', $type)); } // now set rules if they exist if (isset($info['rules'])) { $rules = $info['rules']; } } return $rules; }
public function action_count_not_approved() { return Format::forge(Model_Student::find(count('id'), array('where' => array('course_id' => 0, 'year_level' => 0))))->to_json(); }
/** * Creates the Response and optionally attempts to auto-format the output * * @param string $body * @param int $status * @param string $mime * @param array $headers * @param string $accept_header * @return Response * * @throws OutOfRangeException if an accept header was specified, but the mime type isn't in it */ public function set_response($body, $status, $mime = null, $headers = array(), $accept_header = null) { // did we use an accept header? If so, validate the returned mimetype if (!$this->mime_in_header($mime, $accept_header)) { throw new \OutOfRangeException('The mimetype "' . $mime . '" of the returned response is not acceptable according to the accept header send.'); } // do we have auto formatting enabled and can we format this mime type? if ($this->auto_format and array_key_exists($mime, static::$auto_detect_formats)) { $body = \Format::forge($body, static::$auto_detect_formats[$mime])->to_array(); } $this->response = \Response::forge($body, $status, $headers); return $this->response; }
/** * Loads all currency rate data from service provider * * @access protected * @param string $from_currency A string name of currency available in static::$currencies * @return void */ protected function fetch_currency_rate($from_currency) { Cache::forge('hybrid.currency.' . $from_currency, Config::get('hybrid.currency.cache', array())); if (!array_key_exists($from_currency, static::$currencies)) { throw new FuelException(__METHOD__ . ": Unable to use unknown currency {$from_currency}"); } try { $this->currency_rates = Cache::get('hybrid.currency.' . $from_currency); } catch (CacheNotFoundException $e) { $search = array('{AMOUNT}', '{FROM}', '{TO}'); // load data for each currency, this might take awhile foreach (static::$currencies as $cur => $name) { $replace = array('1', $from_currency, $cur); $url = str_replace($search, $replace, static::$service); try { $data = Curl::get($url)->setopt(array(CURLOPT_BINARYTRANSFER => 1, CURLOPT_RETURNTRANSFER => true, CURLOPT_MAXREDIRS => 5, CURLOPT_HEADER => 0, CURLOPT_USERAGENT => "Fuel PHP framework - \\Hybrid\\Currency class"))->execute(); $body = $data->body; } catch (FuelException $e) { $body = file_get_contents($url); } // this is rather hackish, the return body from either Curl or file_get_contents can't be use directly with json_decode foreach (array("lhs", "rhs", "error", "icc") as $key) { $body = str_replace($key . ":", '"' . $key . '":', $body); } // need to decode this first $data = json_decode($body); if (null !== $data and false !== $data->icc) { $conversion = \Format::forge($body, 'json')->to_array(); $tmp = explode(' ', $conversion['rhs']); $rate = array_shift($tmp); $this->currency_rates[$cur] = (double) $rate; } } Cache::set('hybrid.currency.' . $from_currency, $this->currency_rates); } }
/** * Response * * Takes pure data and optionally a status code, then creates the response * * @param mixed * @param int * @return object Response instance */ protected function response($data = array(), $http_status = null) { if (is_array($data) and empty($data) or $data == '') { $this->response->status = $this->no_data_status; return $this->response; } $http_status or $http_status = $this->http_status; // If the format method exists, call and return the output in that format if (method_exists('Format', 'to_' . $this->format)) { // Set the correct format header $this->response->set_header('Content-Type', $this->_supported_formats[$this->format]); // Set the formatted response $this->response->body(\Format::forge($data)->{'to_' . $this->format}()); // Set the reponse http status $http_status and $this->response->status = $http_status; } else { $this->response->body((string) $data); } return $this->response; }
/** * Function to encode input array depending on the content type * * @param array $input * @return mixed encoded output */ protected function encode(array $input) { // Detect the request content type, default to 'text/plain' $content_type = isset($this->headers['Content-Type']) ? $this->headers['Content-Type'] : $this->response_info('content_type', 'text/plain'); // Get the correct format for the current content type $format = \Arr::key_exists(static::$auto_detect_formats, $content_type) ? static::$auto_detect_formats[$content_type] : null; switch ($format) { // Format as XML case 'xml': /** * If the input array has one item in the top level * then use that item as the root XML element. */ if (count($input) === 1) { $base_node = key($input); return \Format::forge($input[$base_node])->to_xml(null, null, $base_node); } else { return \Format::forge($input)->to_xml(); } break; // Format as JSON // Format as JSON case 'json': return \Format::forge($input)->to_json(); break; // Format as PHP Serialized Array // Format as PHP Serialized Array case 'serialize': return \Format::forge($input)->to_serialize(); break; // Format as PHP Array // Format as PHP Array case 'php': return \Format::forge($input)->to_php(); break; // Format as CSV // Format as CSV case 'csv': return \Format::forge($input)->to_csv(); break; default: if (count($input) === 1 and key($input) === 'form-data') { // multipart/form-data return $input['form-data']; } else { //application/x-www-form-urlencoded return http_build_query($input, null, '&'); } break; } }
/** * Manually parse the response into the proper format * * @param array $response_array The array of response data * @return string The parsed response in the desired format */ public static function prepare_response(array $response_array) { $format = \Session::get('response_format', 'json'); // Make sure we can create it in that format if ($format === 'array' || !method_exists('Format', 'to_' . $format)) { $format = 'json'; } // XML needs the REST basenode from the config, not the one from the \Format config. if ($format === 'xml') { return \Format::forge($response_array)->{'to_' . $format}(null, null, \Config::get('rest.xml_basenode', 'xml')); } // Anything other than XML return \Format::forge($response_array)->{'to_' . $format}(); }
/** * Response * * Takes pure data and optionally a status code, then creates the response * * @param mixed * @param int */ protected function response($data = array(), $http_code = 200) { if (is_array($data) and empty($data) or $data == '') { $this->response->status = 404; return; } $this->response->status = $http_code; // If the format method exists, call and return the output in that format if (method_exists('Format', 'to_' . $this->format)) { // Set the correct format header $this->response->set_header('Content-Type', $this->_supported_formats[$this->format]); $this->response->body(Format::forge($data)->{'to_' . $this->format}()); } else { $this->response->body((string) $data); } }
/** * Attempts to parse a file containing data for import */ public static function parseImportFile($path) { $data = null; $columns = null; $output = array(); // Work out some basic config settings \Config::load('format', true); // Work out the format from the extension $pathinfo = pathinfo($path); $format = strtolower($pathinfo['extension']); // Stop if we don't support the format if (!static::supportsFormat($format)) { throw new \Exception(\Lang::get('admin.errors.import.file_format_unknown')); } // Work out how to parse the data switch ($format) { case 'xls': case 'xlsx': $data = \Format::forge($path, 'xls')->to_array(); $first = array_shift($data); $columns = is_array($first) ? array_filter(array_map(function ($key) { return \Inflector::friendly_title($key, '_', true); }, array_values($first))) : array(); break; default: $data = @file_get_contents($path); if (strpos($data, "\n") !== false) { \Config::set('format.csv.regex_newline', "\n"); } else { if (strpos($data, "\r") !== false) { \Config::set('format.csv.regex_newline', "\r"); } } $data = \Format::forge($data, $format)->to_array(); // Find out some stuff... $first = \Arr::get($data, '0'); $columns = is_array($first) ? array_map(function ($key) { return \Inflector::friendly_title($key, '_', true); }, array_keys($first)) : array(); break; } if (count($columns) > 0) { foreach ($data as $num => $row) { $values = array_values($row); $filtered = array_filter($values); if (count($values) > count($columns)) { $values = array_slice($values, 0, count($columns)); } else { if (count($values) < count($columns)) { while (count($values) < count($columns)) { $values[] = null; } } } if (!empty($filtered)) { $output[] = array_combine($columns, $values); } } } else { $columns = $data = $output = null; } // Stop if there's no data by this point if (!$data) { throw new \Exception(\Lang::get('admin.errors.import.file_parse_error')); } return array('columns' => $columns, 'data' => $output); }
/** * Response * * Takes pure data and optionally a status code, then creates the response * * @param mixed * @param int * @return object Response instance */ protected function response($data = array(), $http_status = null) { // set the correct response header if (method_exists('Format', 'to_' . $this->format)) { $this->response->set_header('Content-Type', $this->_supported_formats[$this->format]); } // no data returned? Set the NO CONTENT status on the response if (is_array($data) and empty($data) or $data == '') { $this->response->status = $this->no_data_status; return $this->response; } // make sure we have a valid return status $http_status or $http_status = $this->http_status; // If the format method exists, call and return the output in that format if (method_exists('Format', 'to_' . $this->format)) { // Handle XML output if ($this->format === 'xml') { // Detect basenode $xml_basenode = $this->xml_basenode; $xml_basenode or $xml_basenode = \Config::get('rest.xml_basenode', 'xml'); // Set the XML response $this->response->body(\Format::forge($data)->{'to_' . $this->format}(null, null, $xml_basenode)); } else { // Set the formatted response $this->response->body(\Format::forge($data)->{'to_' . $this->format}()); } } else { $this->response->body($data); } // Set the reponse http status $http_status and $this->response->status = $http_status; return $this->response; }
/** * Loads in the given file and parses it. * * @param string $file File to load * @return array */ protected function load_file($file) { $contents = $this->parse_vars(file_get_contents($file)); return \Format::forge($contents, 'yaml')->to_array(); }
/** * Test for Format::forge($foo)->to_json() * * @test */ public function test_to_json() { $array = array('articles' => array(array('title' => 'test', 'author' => 'foo', 'tag' => '<tag>', 'apos' => 'McDonald\'s', 'quot' => '"test"', 'amp' => 'M&M'))); $expected = '{"articles":[{"title":"test","author":"foo","tag":"\\u003Ctag\\u003E","apos":"McDonald\\u0027s","quot":"\\u0022test\\u0022","amp":"M\\u0026M"}]}'; $this->assertEquals($expected, Format::forge($array)->to_json()); // pretty json $expected = '{ "articles": [ { "title": "test", "author": "foo", "tag": "\\u003Ctag\\u003E", "apos": "McDonald\\u0027s", "quot": "\\u0022test\\u0022", "amp": "M\\u0026M" } ] }'; $this->assertEquals($expected, Format::forge($array)->to_json(null, true)); // change config options $config = \Config::get('format.json.encode.options'); \Config::set('format.json.encode.options', 0); $expected = <<<EOD {"articles":[{"title":"test","author":"foo","tag":"<tag>","apos":"McDonald's","quot":"\\"test\\"","amp":"M&M"}]} EOD; $this->assertEquals($expected, Format::forge($array)->to_json()); // pretty json $expected = <<<EOD { \t"articles": [ \t\t{ \t\t\t"title": "test", \t\t\t"author": "foo", \t\t\t"tag": "<tag>", \t\t\t"apos": "McDonald's", \t\t\t"quot": "\\"test\\"", \t\t\t"amp": "M&M" \t\t} \t] } EOD; $this->assertEquals($expected, Format::forge($array)->to_json(null, true)); // restore config options \Config::set('format.json.encode.options', $config); }
public function generate_model($table_name, $db = null) { $table_class = \Inflector::classify($table_name); // Generate the full path for the model $file_path = APPPATH . 'classes' . DS . 'model' . DS; $file_path .= str_replace('_', '/', strtolower($table_class)) . '.php'; if (file_exists($file_path)) { \Cli::error('Model already found for database table ' . $table_name); $answer = \Cli::prompt('Overwrite model?', array('y', 'n')); if ($answer == 'n') { \Cli::write('Existing model not overwritten.'); return false; } } $columns = \DB::list_columns($table_name, null, $db); \Cli::write('Found ' . count($columns) . " columns for the {$table_name} database table.", 'green'); $model_properties = array(); foreach ($columns as $column) { // Process some of the column info to allow easier detection list($column_type, $column_unsigned) = explode(' ', $column['data_type'] . ' '); // Concatenated space stops an error happening when data_type has no spaces // A hack to detect Bool data types if ($column_type == 'tinyint' and $column['display'] == 1) { $column_type = 'bool'; } // Basic Properties $column_properties = array('data_type' => in_array($column_type, static::$data_typing_types) ? $column_type : 'string', 'label' => \Inflector::humanize($column['name']), 'null' => $column['null']); $column['default'] and $column_properties['default'] = $column['default']; // Validation // TODO: Add thresholds rather than having rediculously high max values $column_validation = array(); $column['null'] or $column_validation[] = 'required'; if ($column_type == 'bool') { $column_validation = array('required'); } elseif (key_exists($column_type, static::$string_max_lengths)) { $column_validation['max_length'] = array((int) min($column['character_maximum_length'], static::$string_max_lengths[$column_type])); } elseif ($column['type'] == 'int') { $display_max = (int) str_repeat(9, $column['display']); $column_validation['numeric_min'] = array((int) $column['min']); $column_validation['numeric_max'] = array((int) min($column['max'], $display_max)); } elseif ($column['type'] == 'float') { $max = (double) (str_repeat(9, $column['numeric_precision'] - $column['numeric_scale']) . '.' . str_repeat(9, $column['numeric_scale'])); $min = substr($column['data_type'], -8) == 'unsigned' ? 0 : $max * -1; $column_validation['numeric_min'] = array($min); $column_validation['numeric_max'] = array($max); } // Form $column_form = array('type' => 'text'); if (in_array($column['name'], array('id', 'created_at', 'updated_at'))) { $column_form['type'] = false; } else { $column['default'] and $column_form['value'] = $column['default']; switch ($column_type) { case 'char': case 'varchar': case 'tinytext': case 'tinyblob': isset($column_validation['max_length']) and $column_form['maxlength'] = $column_validation['max_length'][0]; break; case 'text': case 'blob': case 'mediumtext': case 'mediumblob': case 'longtext': case 'longblob': $column_form['type'] = 'textarea'; break; case 'enum': case 'set': $column_form['type'] = 'select'; $column_form['options'] = array(); break; case 'bool': $column_form['type'] = 'radio'; $column_form['options'] = array(1 => 'Yes', 0 => 'No'); break; case 'decimal': case 'double': case 'float': $column_form['step'] = floatval('0.' . str_repeat(9, $column['numeric_scale'])); // break is intentionally missing // break is intentionally missing case 'tinyint': case 'smallint': case 'int': case 'mediumint': case 'bigint': $column_form['type'] = 'number'; isset($column_validation['numeric_min']) and $column_form['min'] = $column_validation['numeric_min'][0]; isset($column_validation['numeric_max']) and $column_form['max'] = $column_validation['numeric_max'][0]; break; /* @TODO case 'date': case 'datetime': case 'time': case 'timestamp': break;*/ } } $column_properties['validation'] = $column_validation; $column_properties['form'] = $column_form; $model_properties[$column['name']] = $column_properties; } $model_properties_str = str_replace(array("\n", ' ', 'array ('), array("\n\t", "\t", 'array('), \Format::forge($model_properties)->to_php()); $model_properties_str = preg_replace('/=>\\s+array/m', '=> array', $model_properties_str); $model_str = <<<MODEL <?php class Model_{$table_class} extends \\Orm\\Model { protected static \$_table_name = '{$table_name}'; protected static \$_properties = {$model_properties_str}; protected static \$_observers = array( 'Orm\\Observer_Validation' => array( 'events' => array('before_save'), ), 'Orm\\Observer_Typing' => array( 'events' => array('before_save', 'after_save', 'after_load'), ), MODEL; if (isset($model_properties['created_at'])) { $model_str .= <<<MODEL 'Orm\\Observer_CreatedAt' => array( 'events' => array('before_insert'), 'mysql_timestamp' => false, 'property' => 'created_at', ), MODEL; } if (isset($model_properties['updated_at'])) { $model_str .= <<<MODEL 'Orm\\Observer_UpdatedAt' => array( 'events' => array('before_save'), 'mysql_timestamp' => false, 'property' => 'updated_at', ), MODEL; } $model_str .= <<<MODEL ); } MODEL; // Make sure the directory exists is_dir(dirname($file_path)) or mkdir(dirname($file_path), 0775, true); // Show people just how clever FuelPHP can be \File::update(dirname($file_path), basename($file_path), $model_str); return true; }
/** * Hydration from raw request (xml/json requests) * * @param string $type input type */ protected static function hydrate_raw_input($type) { static::$php_input === null and static::$php_input = file_get_contents('php://input'); static::${$type} = \Security::clean(\Format::forge(static::$php_input, $type)->to_array()); }
/** * Response * * Takes pure data and optionally a status code, then creates the response * * @param mixed * @param int * @return object Response instance */ protected function response($data = array(), $http_status = null) { // set the correct response header if (method_exists('Format', 'to_' . $this->format)) { $this->response->set_header('Content-Type', $this->_supported_formats[$this->format]); } // no data returned? if (is_array($data) and empty($data) or $data == '') { // override the http status with the NO CONTENT status $http_status = $this->no_data_status; } // make sure we have a valid return status $http_status or $http_status = $this->http_status; // If the format method exists, call and return the output in that format if (method_exists('Format', 'to_' . $this->format)) { // Handle XML output if ($this->format === 'xml') { // Detect basenode $xml_basenode = $this->xml_basenode; $xml_basenode or $xml_basenode = \Config::get('rest.xml_basenode', 'xml'); // Set the XML response $this->response->body(\Format::forge($data)->{'to_' . $this->format}(null, null, $xml_basenode)); } else { // Set the formatted response $this->response->body(\Format::forge($data)->{'to_' . $this->format}()); } } elseif (is_array($data) or is_object($data) and !method_exists($data, '__toString')) { if (\Fuel::$env == \Fuel::PRODUCTION) { // not acceptable in production $http_status = 406; $this->response->body('The requested REST method returned an array or object, which is not compatible with the output format "' . $this->format . '"'); } else { // convert it to json so we can at least read it while we're developing $this->response->body('The requested REST method returned an array or object:<br /><br />' . \Format::forge($data)->to_json(null, true)); } } else { $this->response->body($data); } // Set the reponse http status $http_status and $this->response->status = $http_status; return $this->response; }