protected function verifyConsole() { $request = $this->getRequest(); if (!$request instanceof ConsoleRequest) { throw RuntimeException(sprintf('%s can only be run via the Console', __METHOD__)); } }
/** @inheritdoc */ public function getRestaurantUri($restaurantId) { $config = $this->configRestaurant($restaurantId); if (isset($config['uri'])) { return $config['uri']; } throw \RuntimeException('Restaurant has no URI configured'); }
public function createTwigFileSystemLoader() { $dir = $this->getTemplateDir(); if (!file_exists($dir)) { throw RuntimeException("Directory {$dir} for TemplateView does not exist."); } return new Twig_Loader_Filesystem($dir); }
public static function charger() { if (null !== self::$_instance) { throw new RuntimeException(sprintf('%s is already started', __CLASS__)); } self::$_instance = new self(); if (!spl_autoload_register(array(self::$_instance, '_autoload'), false)) { throw RuntimeException(sprintf('%s : Could not start the autoload', __CLASS__)); } }
public function getEventName() { if (empty($this->eventName)) { if (!static::EVENT_NAME) { throw \RuntimeException('Your must have set one event name'); } return static::EVENT_NAME; } return $this->eventName; }
public function getService($name) { if ($name === 'solve_media') { return $this->app->SolveMediaService; } else { if ($name === 'recaptcha') { return $this->app->RecaptchaService; } } throw RuntimeException(); }
/** * Does file replacements. * * @param array $matches */ protected function _replace($matches) { $required = empty($matches[2]) ? $matches[4] : $matches[2]; $filename = $this->_Scanner->find($required); if (!$filename) { throw RuntimeException('Could not find dependency'); } if (empty($this->_loaded[$filename])) { return $this->input($filename, file_get_contents($filename)); } return ''; }
/** * Create new avatar image for current authenticated user * @param string $sUserAvatarFilePath * @throws \InvalidArgumentException * @throws \RuntimeException * @throws \DomainException * @throws \LogicException * @return \BoilerAppUser\Service\UserAccountService */ public function changeAuthenticatedUserAvatar($sUserAvatarFilePath) { if (!is_string($sUserAvatarFilePath)) { throw new \InvalidArgumentException('User avatar path expects string, "' . gettype($sUserAvatarFilePath) . '" given'); } if (!is_readable($sUserAvatarFilePath)) { throw new \InvalidArgumentException('User avatar path "' . $sUserAvatarFilePath . '" is not a readable file path'); } if (!($aImagesInfos = @getimagesize($sUserAvatarFilePath)) || empty($aImagesInfos[2])) { \RuntimeException('An error occurred while retrieving user avatar "' . $sUserAvatarFilePath . '" infos'); } switch ($aImagesInfos[2]) { case IMAGETYPE_JPEG: if (!($oImage = imagecreatefromjpeg($sUserAvatarFilePath))) { throw new \RuntimeException('An error occurred during creating image from "jpeg" user avatar "' . $sUserAvatarFilePath . '"'); } break; case IMAGETYPE_GIF: if (!($oImage = imagecreatefromgif($sUserAvatarFilePath))) { throw new \RuntimeException('An error occurred during creating image from "gif" user avatar "' . $sUserAvatarFilePath . '"'); } break; case IMAGETYPE_PNG: if (!($oImage = imagecreatefrompng($sUserAvatarFilePath))) { throw new \RuntimeException('An error occurred during creating image from "png" user avatar "' . $sUserAvatarFilePath . '"'); } break; default: throw new \DomainException('File type "' . $aImagesInfos[2] . '" is not supported for avatar'); } //Crop image if (!($oNewImage = imagecreatetruecolor(128, 128))) { throw new \RuntimeException('An error occurred during creating new image for croping user avatar'); } if (!imagecopyresampled($oNewImage, $oImage, 0, 0, 0, 0, 128, 128, imagesx($oImage), imagesy($oImage))) { throw new \RuntimeException('An error occurred during croping user avatar'); } $aConfiguration = $this->getServiceLocator()->get('Config'); if (empty($aConfiguration['paths']['avatarsPath'])) { throw new \LogicException('Avatars directory path is undefined'); } if (!is_string($aConfiguration['paths']['avatarsPath'])) { throw new \LogicException('Avatars directory path expects string, "' . gettype($aConfiguration['paths']['avatarsPath']) . '" given'); } if (!is_dir($aConfiguration['paths']['avatarsPath'])) { throw new \LogicException('Avatars directory path expects string, "' . $aConfiguration['paths']['avatarsPath'] . '" is not a valid directory'); } //Save avatar if (!imagepng($oNewImage, $aConfiguration['paths']['avatarsPath'] . DIRECTORY_SEPARATOR . $this->getServiceLocator()->get('AccessControlService')->getAuthenticatedAuthAccess()->getAuthAccessUser()->getUserId() . '-avatar.png')) { throw new \RuntimeException('An error occurred during saving user avatar'); } return $this; }
public function ensureWritableDir($path, $mode = 0777) { $dir = $this->getPath($path); if (!is_dir($dir)) { if (!mkdir($dir, $mode, true)) { throw \RuntimeException('Cant Create ' . $dir); } } if (!is_writable($dir)) { if (!chmod($dir, $mode)) { throw \RuntimeException('Cant Change Permission ' . $dir); } } return true; }
public function actionPerformed($action) { switch ($action) { case self::do_use: $this->state->doUse($this); break; case self::do_alarm: $this->state->doAlarm($this); break; case self::do_phone: $this->state->doPhone($this); break; default: throw RuntimeException(__LINE__ . ' ' . __METHOD__); break; } }
/** * ensures a directory exist, by creating it if it does no & it's possible to * * @param string $dir directory */ function ensure_directory($dir) { if (file_exists($dir)) { if (!is_dir($dir)) { throw new InvalidArgumentException($dir); } } else { $dir = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $dir)); $cDir = ''; //complete dir foreach ($dir as $d) { $cDir .= $d . '/'; if (!file_exists($cDir) && !@mkdir($cDir)) { throw RuntimeException("can't create {$cDir}"); } } } }
public function payCallBackAction(Request $request, $name) { $controller = $this; $status = $this->doPayNotify($request, $name, function ($success, $order) use(&$controller) { if (!$success) { return; } if ($order['targetType'] != 'course') { throw \RuntimeException('非课程订单,加入课程失败。'); } $info = array('orderId' => $order['id'], 'remark' => empty($order['data']['note']) ? '' : $order['data']['note']); if (!$controller->getCourseService()->isCourseStudent($order['targetId'], $order['userId'])) { $controller->getCourseService()->becomeStudent($order['targetId'], $order['userId'], $info); $controller->getLogService()->info('order', 'callback_success', "paycalknotify action"); } return; }); $callback = "<script type='text/javascript'>window.location='objc://alipayCallback?" . $status . "';</script>"; return new Response($callback); }
/** * Initialize image information * @throws RuntimeException */ public function init($file) { if (!file_exists($file)) { throw \InvalidArgumentException("source image does not exists"); } $this->file = $file; if (!($info = getimagesize($this->file))) { throw new \RuntimeException("source image does not exists : " . $this->file); } $this->width = $info[0]; $this->height = $info[1]; $mime = $info['mime']; $this->type = str_replace('image/', '', $mime); $func = 'imagecreatefrom' . $this->type; if (!function_exists($func)) { throw \RuntimeException("Format not supported"); } $this->file = $func($this->file); return $this; }
/** * Retrieves the exchange rate of the USD specified in MXN as calculated * from "http://dof.gob.mx/indicadores.php". * * @throws RuntimeException When client could not connect to the webserver * at dof.gob.mx and thus USD value could not be retrieved. * * @return float */ public function usdMxn() { $query = http_build_query(['cod_tipo_indicador' => '158', 'dfecha' => Carbon::now()->subMonth()->format('d/m/Y'), 'hfecha' => Carbon::now()->format('d/m/Y')]); $url = 'http://dof.gob.mx/indicadores_detalle.php?' . $query; $webContent = file_get_contents($url); if (!$webContent) { throw RuntimeException("Couldn't connect to dof.gob.mx server!"); } $dom = new \DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML($webContent); $items = $dom->getElementsByTagName('tr'); $entries = []; foreach ($items as $tag) { if (!$tag->hasAttribute('class')) { continue; } if ($tag->getAttribute('class') != 'Celda 1') { continue; } $entries[] = $this->helpers->parseNodes($tag->childNodes); } return $this->helpers->mostRecentEntry($entries)['rate']; }
public function parse() { throw RuntimeException('It need use parse() function in sub class.'); }
require_once COM_FABRIK_FRONTEND . '/controller.php'; require_once COM_FABRIK_FRONTEND . '/controllers/list.php'; // $$$rob looks like including the view does something to the layout variable $input = $app->input; $origLayout = $input->get('layout'); require_once COM_FABRIK_FRONTEND . '/views/list/view.html.php'; $input->set('layout', $origLayout); require_once COM_FABRIK_FRONTEND . '/views/package/view.html.php'; JModelLegacy::addIncludePath(COM_FABRIK_FRONTEND . '/models'); JTable::addIncludePath(COM_FABRIK_BASE . '/administrator/components/com_fabrik/tables'); $document = JFactory::getDocument(); require_once COM_FABRIK_FRONTEND . '/controllers/package.php'; require_once COM_FABRIK_FRONTEND . '/views/form/view.html.php'; $listId = (int) $params->get('list_id', 0); if ($listId === 0) { throw RuntimeException('Fabrik Module: No list specified', 500); } $listels = json_decode($params->get('list_elements')); if (isset($listels->show_in_list)) { $input->set('fabrik_show_in_list', $listels->show_in_list); } $layout = $params->get('fabriklayout', 'default'); $input->set('layout', $layout); $moduleclass_sfx = $params->get('moduleclass_sfx', ''); $listId = (int) $params->get('list_id', 1); $viewName = 'list'; $viewType = $document->getType(); $controller = new FabrikControllerList(); // Set the default view name from the Request $view = clone $controller->getView($viewName, $viewType); // Push a model into the view
public function importSif($filename) { if (empty($this->Id)) { throw RuntimeException("Numerical model must have ID (i.e. be saved) before calling importSif"); } $sif = file_get_contents($filename); /* $matches = []; preg_match_all("/\\$([_a-zA-Z][_a-zA-Z0-9]*)/", $sif, $matches); $this->definition = $sif; foreach ($matches[1] as $key) { if (strpos($key, 'CONSTANT_') === 0 || strpos($key, 'SETTING_') === 0 || strpos($key, 'PARAMETER_') === 0) $this->placeholder($key); } */ $this->loadDefinitionFromString($sif); $this->save(); }
<?php // KO with native exceptions throw RuntimeException(); throw \RuntimeException(); throw A(); class A extends Exception { } // OK, it is a function throw B(); function B() { } // OK, because it's a function too. throw C(); function C() { } class C extends Exception { } // KO, as D is not an exception throw D(); class D { }
/** * Adds or updates a data pair. * @access public * @param string $key Data pair key * @param string $value Data pair value * @param integer $expiration Data life time in seconds or expiration timestamp * @return void */ public function set($key, $value, $expiration = NULL) { $this->lock->lock(); try { $expiration = $expiration ? $expiration : $this->expiration; $entries = json_decode($this->file->readString(), TRUE); if (!isset($entries[$this->context])) { $entries[$this->context] = array(); } $entries[$this->context][$key] = array('value' => serialize($value), 'timestamp' => time(), 'expires' => time() + (int) $expiration); $this->file->writeString(json_encode($entries)); $this->lock->unlock(); return TRUE; } catch (Exception $e) { $this->lock->unlock(); throw RuntimeException('Setting cache key failed: ' . $e->getMessage()); } }
/** * /domain/<xxx>/<yyy>Controller.php の <zzz>Action を実行 */ public function dispatch() { // パラメーター取得 $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $arg = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY); // 短いURL用 if ('' !== $this->get('s', '')) { $urlId = intval($this->get('s', '')); $db = new DataBase(); $shortUrl = $db->selectQuery('tbl_short_url')->where('url_id', $urlId)->fetch(); if (isset($shortUrl['url'])) { $this->redirect($shortUrl['url']); } } // パラメーターを / で分割 $params = array_map(function ($prm) { if ('' == $prm or 'index.php' == $prm) { return 'index'; } return $prm; }, array_slice(explode('/', $path), 1)); $this->setReadDir('/'); if (2 === count($params)) { $params[2] = 'index'; } if (2 > count($params)) { $params = ['index', 'index', 'index']; } else { $dirs = array_map(function ($param) { return ucfirst($param); }, array_slice($params, 1, -1)); $this->setReadDir('/' . implode('/', $dirs) . '/'); } $paramCount = count($params); // パラメータより取得したコントローラー名によりクラス振分け $indexName = strtolower($params[0]); $actionBase = $params[$paramCount - 1]; $className = ucfirst($indexName) . 'Controller'; $this->setReadFile($indexName, $className); // ない場合はindexへ if (!file_exists($this->controllerFile)) { error_log('file "' . $this->controllerFile . '" is not found. move to index'); $this->setReadDir('/'); $indexName = 'index'; $actionBase = $indexName; $className = 'IndexController'; $this->setReadFile($indexName, $className); if (!file_exists($this->controllerFile)) { echo $this->controllerFile; error_log('index file is not found.'); throw RuntimeException('index file not found.'); } } // クラスファイル読込 require_once $this->controllerFile; // クラスインスタンス生成 $classFullName = '\\src\\Controller' . str_replace('/', '\\', $this->readDir) . $className; $controllerInstance = new $classFullName(); // 土台smartyファイル読み込み $controllerInstance->append('view.html'); $controllerInstance->append('Elements/header.html'); $controllerInstance->append('Elements/footer.html'); $controllerInstance->append('Elements/SNSbutton.html'); // viewファイルを取得 $actionMethod = 'indexAction'; $this->viewFile = $controllerInstance->getViewFile($this->readDir, $actionBase, $actionMethod); // アクションメソッドを実行 if (is_array($actionMethod)) { $controllerInstance->{$actionMethod}[0](array_slice($actionMethod, 1)); } else { $controllerInstance->{$actionMethod}(); } // smarty 親変数 $controllerInstance->set('nowtime', (new DateTime('NOW'))->format('Y-m-d H:i:s')); $controllerInstance->set('pageName', $params[1]); // smarty表示 $controllerInstance->show($this->viewFile); }
/** * Merges a page (and its subpages) into this navigation. * If the page already exists in the navigation, then it attempts to add * any new subpages of the page to it. If a subpages already exists in the navigation, then it * it recursively attempts to add its new subpages to it, and so on. * * @param Zend_Navigation_Page $page page to be merged * @return Zend_Navigation_Container $parentContainer the suggested parentContainer for the page. * The parentContainer must already be in the navigation and remain so throughout the merge. * @throws Zend_Navigation_Exception if a subpage is invalid * @throws RuntimeException if the page or parentContainer is invalid */ public function mergePage(Zend_Navigation_Page $page, Zend_Navigation_Container $parentContainer = null) { if (!$page->uid) { // we assume that every page has already been normalized throw new RuntimeException(__('The page must be normalized and have a valid uid.')); } if ($parentContainer === null) { $parentContainer = $this; } // save the child pages and remove them from the current page $childPages = $page->getPages(); $page->removePages($childPages); if (!($oldPage = $this->getPageByUid($page->uid))) { if ($parentContainer !== $this && !$this->hasPage($parentContainer, true)) { // we assume parentContainer is either the navigation object // or a descendant page of the navigation object throw RuntimeException(__('The parent container must either be the navigation object' . ' or a descendant subpage of the navigation object.')); } // add the page to the end of the parent container $pageOrder = $this->_getLastPageOrderInContainer($parentContainer) + 1; $page->setOrder($pageOrder); $this->addPageToContainer($page, $parentContainer); // set the new parent page $parentPage = $page; } else { // set the new parent page $parentPage = $oldPage; } // merge the child pages foreach ($childPages as $childPage) { $this->mergePage($childPage, $parentPage); } }
/** * Update the current stored file * * @return bool */ protected function update() { if (empty($this->fileProperties)) { return false; } $user = JFactory::getUser(); $date = JFactory::getDate(); $table = JTable::getInstance('File', 'MediaTable'); $path = str_replace(JPATH_ROOT . '/', '', dirname($this->fileProperties['path'])); $hash = null; if ($this->fileAdapter instanceof MediaModelFileAdapterInterface) { $hash = $this->fileAdapter->getHash(); } $data = array('id' => $this->id, 'filename' => basename($this->fileProperties['path']), 'path' => $path, 'md5sum' => $hash, 'user_id' => $user->id, 'modified_by' => $user->id, 'modified' => $date->toSql(), 'adapter' => 'local', 'published' => 1, 'ordering' => 1); if (!$table->save($data)) { throw RuntimeException($table->getError()); return false; } return $this->id; }
/** * Inserisce l'utente negli stessi gruppi cui è iscritta la società di appartenenza. * Operazione necessaria per l'accesso ai form di discussione. * * @param string $coupon * @return bool */ public function set_user_groups($coupon) { try { if (empty($coupon)) { throw new BadMethodCallException('Parametro non valido: coupon non è impostato', E_USER_ERROR); } // ottendo l'id della società $query = 'SELECT id_societa FROM #__gg_coupon WHERE coupon=\'' . $coupon . '\' LIMIT 1'; if ($this->_dbg) { $this->_japp->enqueueMessage($query); } $this->_db->setQuery($query); if (false === ($results = $this->_db->loadAssoc())) { throw new RuntimeException($this->_db->getErrorMsg(), E_USER_ERROR); } $company_id = filter_var($results['id_societa'], FILTER_VALIDATE_INT); if (empty($company_id)) { throw RuntimeException('Cannot get company ID from database', E_USER_ERROR); } // aggiorno i gruppi dell'utente $query = 'INSERT INTO #__user_usergroup_map (user_id, group_id) SELECT ' . $this->_userid . ', g.id AS group_id FROM #__usergroups AS g INNER JOIN #__users AS u ON u.name=g.title WHERE u.id=' . $company_id; if ($this->_dbg) { $this->_japp->enqueueMessage($query); } $this->_db->setQuery($query); if (false === ($results = $this->_db->query())) { throw new RuntimeException($this->_db->getErrorMsg(), E_USER_ERROR); } } catch (Exception $e) { return false; } }
/** * Takes care of restarting the whole parsing loop if it encounters a "(" or ")" * token, consumes a pure string including whitespace or passes the torch * down to the evaluateTerm method * * @return mixed */ public function parseTermToken() { $t = $this->peek(); if ($this->isTerm($t)) { $this->consume($t); return $this->evaluateTerm($t, $this->context); } throw \RuntimeException('end of line, you should never have reached this point.'); }
/** * Atomically read, filter, and write a file. * * @param string $file * @param callable $filter * A function which accepts full file content as input, * and returns new content as output. * @param int|float $maxWait * @param int $maxSize * @return bool * @throws */ public function update($file, $filter, $maxWait = 5.0) { $mode = file_exists($file) ? 'r+' : 'w+'; if (!($fh = fopen($file, $mode))) { throw new \RuntimeException("Failed to open"); } $start = microtime(TRUE); do { $locked = flock($fh, LOCK_EX | LOCK_NB); if (!$locked && microtime(TRUE) - $start > $maxWait) { throw new \RuntimeException("Failed to lock"); } if (!$locked) { usleep(rand(20, 100) * 1000); } } while (!$locked); // TODO throw an error $maxSize exceeded. $buf = ''; while (!feof($fh)) { $buf .= fread($fh, 1024 * 1024); } $rawOut = call_user_func($filter, $buf); if (!rewind($fh)) { throw \RuntimeException('Bad rewind'); } if (!ftruncate($fh, 0)) { throw \RuntimeException('Bad truncate'); } if (!fwrite($fh, $rawOut)) { throw \RuntimeException('Bad write'); } flock($fh, LOCK_UN); return fclose($fh); }
/** * Fetch the leaf entity for the given path. * * This method will traverse the given path and find the leaf * entity. If the path does not contain a leaf entity false * will be returned. * * @param array $path Each one of the parts in a path for a field name * @return \Cake\DataSource\EntityInterface|bool * @throws \RuntimeException When properties cannot be read. */ protected function _getEntity($path) { $oneElement = count($path) === 1; if ($oneElement && $this->_isCollection) { return false; } $entity = $this->_context['entity']; if ($oneElement) { return $entity; } if ($path[0] === $this->_rootName) { $path = array_slice($path, 1); } foreach ($path as $prop) { $next = $this->_getProp($entity, $prop); if (!is_array($next) && !$next instanceof Traversable && !$next instanceof Entity) { return $entity; } $entity = $next; } throw \RuntimeException(sprintf('Unable to fetch property "%s"', implode(".", $path))); }
/** * Main entry point for command selectors */ public static function select(Server $srv, CommandSender $sender, array $args) { throw \RuntimeException("Unimplemented select"); }
/** * {@inheritDoc} */ public function offsetUnset($offset) { return \RuntimeException('A PaginatedResult is read only after creation'); }
public static function rfrRequestToXml($hash_in) { $rfr = simplexml_load_string("<RFRRequest />"); if (isset($hash_in['litleSessionId'])) { $rfr->addChild('litleSessionId', $hash_in['litleSessionId']); } else { if (isset($hash_in['merchantId']) && isset($hash_in['postDay'])) { $auFileRequest = $rfr->addChild('accountUpdateFileRequestData'); $auFileRequest->addChild('merchantId', $hash_in['merchantId']); $auFileRequest->addChild('postDay', $hash_in['postDay']); } else { throw RuntimeException('To add an RFR Request, either a litleSessionId or a merchantId and a postDay must be set.'); } } return str_replace("<?xml version=\"1.0\"?>\n", "", $rfr->asXML()); }
/** * @return void */ private function emptyTestDir() { if (empty($this->testDir)) { throw \RuntimeException('Test directory does not exist'); } foreach (glob($this->testDir . DIRECTORY_SEPARATOR . '*') as $file) { chmod($file, 0755); } $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->testDir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST); foreach ($files as $fileinfo) { if ($fileinfo->isDir()) { rmdir($fileinfo->getRealPath()); } else { unlink($fileinfo->getRealPath()); } } }