本文整理汇总了PHP中Exception函数的典型用法代码示例。如果您正苦于以下问题:PHP Exception函数的具体用法?PHP Exception怎么用?PHP Exception使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Exception函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: scaleImageSize
/**
* Calculate the image size by allowed image size.
*
* @param string|array $image
* @param array $allowSize
* @return array
* @throws \Exception
*/
public static function scaleImageSize($image, $allowSize)
{
if (is_string($image)) {
$imageSizeRaw = getimagesize($image);
$imageSize['w'] = $imageSizeRaw[0];
$imageSize['h'] = $imageSizeRaw[1];
} else {
$imageSize = $image;
}
if (!isset($imageSize['w']) or !isset($imageSize['h'])) {
throw \Exception(_a('Raw image width and height data is needed!'));
}
if (!isset($allowSize['image_width']) or !isset($allowSize['image_height'])) {
throw \Exception(_a('The limitation data is needed!'));
}
$scaleImage = $imageSize;
if ($imageSize['w'] >= $imageSize['h']) {
if ($imageSize['w'] > $allowSize['image_width']) {
$scaleImage['w'] = (int) $allowSize['image_width'];
$scaleImage['h'] = (int) ($allowSize['image_width'] * $imageSize['h'] / $imageSize['w']);
}
} else {
if ($imageSize['h'] > $allowSize['image_height']) {
$scaleImage['h'] = (int) $allowSize['image_height'];
$scaleImage['w'] = (int) ($allowSize['image_height'] * $imageSize['w'] / $imageSize['h']);
}
}
return $scaleImage;
}
示例2: get
/**
* Gets the required context.
*
* Getting a context you get access to all the steps
* that uses direct API calls; steps returning step chains
* can not be executed like this.
*
* @throws coding_exception
* @param string $classname Context identifier (the class name).
* @return BehatBase
*/
public static function get($classname)
{
if (!self::init_context($classname)) {
throw Exception('The required "' . $classname . '" class does not exist');
}
return self::$contexts[$classname];
}
示例3: save
public function save(Gyuser_Model_BankAccounts $bank)
{
if (trim($bank->getOpening_date()) == '') {
$opening_date = null;
} else {
$dateArr = explode('/', $bank->getOpening_date());
if (checkdate($dateArr[1], $dateArr[0], $dateArr[2])) {
$stampeddate = mktime(12, 0, 0, $dateArr[1], $dateArr[0], $dateArr[2]);
$opening_date = date("Y-m-d", $stampeddate);
} elseif (checkdate($dateArr[0], '01', $dateArr[1])) {
//in case they have entered only month and year format ex: 02/1993
$stampeddate = mktime(12, 0, 0, $dateArr[0], '01', $dateArr[1]);
$opening_date = date("Y-m-d", $stampeddate);
} else {
throw Exception('The bank opening date is invalid.');
}
}
$data = array("user_id" => $bank->getUser_id(), "bank_name" => $bank->getBank_name(), "account_n" => $bank->getAccount_n(), "branch" => $bank->getBranch(), "opening_date" => $opening_date, "zip_code" => $bank->getZip_code(), "location_capital" => $bank->getLocation_capital());
if (null === ($id = $bank->getId())) {
unset($data['id']);
$id = $this->getDbTable()->insert($data);
return $id;
} else {
unset($data['user_id']);
$id = $this->getDbTable()->update($data, array('id = ?' => $id));
return $id;
}
}
示例4: getName
public final function getName()
{
if (!$this->name) {
throw Exception('You must define name for your shape');
}
return $this->name;
}
示例5: calculateTotalAmount
public function calculateTotalAmount($BillingAgreementDetails, $paymentAmountPreTaxAndShipping, $shippingType)
{
$paymentTotal = $paymentAmountPreTaxAndShipping;
if ($BillingAgreementDetails->getDestination() == null) {
throw Exception("Error - expected to find destination in billing agreement details response" . ", check that correct versions of the widgets have been" . " used to create the Amazon billing agreement Id");
}
$physicalAddress = $BillingAgreementDetails->getDestination()->getPhysicalDestination();
/* *********************************************************************
* Add shipping costs to the total order, based on the country of the
* destination address
* ******************************************************************
*/
if (array_key_exists($physicalAddress->getCountryCode(), $this->_countryCostsMatrix)) {
$paymentTotal = $paymentTotal + $this->_countryCostsMatrix[$physicalAddress->getCountryCode()]->shippingRates[$shippingType];
/* *********************************************************************
* Add tax to the order if the the state or region exists in our
* tax rate map
* ********************************************************************
*/
if (array_key_exists($physicalAddress->getStateOrRegion(), $this->_countryCostsMatrix[$physicalAddress->getCountryCode()]->taxRates)) {
$paymentTotal = $paymentTotal * $this->_countryCostsMatrix[$physicalAddress->getCountryCode()]->taxRates[$physicalAddress->getStateOrRegion()];
}
} else {
$paymentTotal = $paymentTotal + $_this->countryCostsMatrix["Unknown"]->shippingRates[$shippingType];
}
return $paymentTotal;
}
示例6: savePdf
public function savePdf()
{
$pnr = $this->em->getRepository('AppCoreBundle:Pnr')->find($this->id);
if (!$pnr) {
return \Exception('PNR not found');
}
//Trick to prevent cache size exceeded
//set_time_limit(0);
while (ob_get_level()) {
ob_end_clean();
}
ob_implicit_flush(true);
/*
* Construct PDF with Mpdf service
* Layout based on HTML twig template
*/
$service = $this->tfox;
$pdf = $service->getMpdf(array('', 'A4', 8, 'Helvetica', 10, 10, 15, 15, 9, 9, 'L'));
$pdf->AliasNbPages('{NBPAGES}');
$pdf->setTitle('billet-' . date('d-m-Y-H-i', time()) . '.pdf');
$pdf->SetHeader('Billet');
$pdf->SetFooter('{DATE j/m/Y}|{PAGENO}/{NBPAGES}');
$html = $this->templating->renderResponse('AppCoreBundle:Pnr:billetpdf.pdf.twig', array('pnr' => $pnr));
$pdf->WriteHTML($html);
//$url = 'billet-'.$pnr->getNumero().'.pdf';
//$pdf->Output($url, 'F');
$pdf->Output();
/*$this->get('session')->getFlashBag()->add(
'success',
'Le billet a bien été enregistré !'
);*/
//return $this->redirect($this->generateUrl('pnr_emit', array('id' => $id)));
//return $url;
}
示例7: autoedit_createPath
function autoedit_createPath($p, $path = '')
{
//путь до файла или дирректории со * или без, возвращается тот же путь без звёздочки
//Если путь приходит от пользователя нужно проверять и префикс infra/data добавляется автоматически чтобы ограничить места создания
//if(preg_match("/\/\./",$ifolder))return err($ans,'Path should not contain points at the beginning of filename /.');
//if(!preg_match("/^\*/",$ifolder))return err($ans,'First symbol should be the asterisk *.');
if (is_string($p)) {
$p = Path::resolve($p);
$p = explode('/', $p);
$f = array_pop($p);
//достали файл или пустой элемент у дирректории
$f = Path::tofs($f);
} else {
$f = '';
}
$dir = array_shift($p);
//Создаём первую папку в адресе
$dir = Path::tofs($dir);
if ($dir) {
if (!is_dir($path . $dir)) {
$r = mkdir($path . $dir);
} else {
$r = true;
}
if ($r) {
return autoedit_createPath($p, $path . $dir . '/') . $f;
} else {
throw Exception('Ошибка при работе с файловой системой');
}
}
return $path . $dir . '/' . $f;
}
示例8: process
/**
* @param ContainerBuilder $container
*
* @throws \InvalidArgumentException
*/
public function process(ContainerBuilder $container)
{
$config = $container->getExtensionConfig('elastica')[0];
$jsonLdFrameLoader = $container->get('nemrod.elastica.jsonld.frame.loader.filesystem');
$confManager = $container->getDefinition('nemrod.elastica.config_manager');
$filiationBuilder = $container->get('nemrod.filiation.builder');
$jsonLdFrameLoader->setFiliationBuilder($filiationBuilder);
foreach ($config['indexes'] as $name => $index) {
$indexName = isset($index['index_name']) ? $index['index_name'] : $name;
foreach ($index['types'] as $typeName => $settings) {
$jsonLdFrameLoader->setEsIndex($name);
$frame = $jsonLdFrameLoader->load($settings['frame'], null, true, true, true);
$type = !empty($frame['@type']) ? $frame['@type'] : $settings['type'];
if (empty($type)) {
throw \Exception("You must provide a RDF Type.");
}
//type
$typeId = 'nemrod.elastica.type.' . $name . '.' . $typeName;
$indexId = 'nemrod.elastica.index.' . $name;
$typeDef = new DefinitionDecorator('nemrod.elastica.type.abstract');
$typeDef->replaceArgument(0, $type);
$typeDef->setFactory(array(new Reference($indexId), 'getType'));
$typeDef->addTag('nemrod.elastica.type', array('index' => $name, 'name' => $typeName, 'type' => $type));
$container->setDefinition($typeId, $typeDef);
//registering config to configManager
$confManager->addMethodCall('setTypeConfigurationArray', array($name, $typeName, $type, $frame));
}
}
}
示例9: closureTestMethod
protected function closureTestMethod($name, $value, $query)
{
if (!is_array($value) || count($value) !== 2) {
throw \Exception("Value for {$name} not correctly passed through closure!");
}
return $query->where('name', '=', $value[0])->where('test_related_model_id', '=', $value[1]);
}
示例10: getTotalResults
public function getTotalResults()
{
if (!$this->isPaged()) {
throw Exception("This API result has no paging information");
}
return $this->pagingData['total_results'];
}
示例11: editTourAction
public function editTourAction()
{
$form = $this->view->form = new Yntour_Form_Tour_Create();
$model = new Yntour_Model_DbTable_Tours();
$id = $this->_getParam('tour_id', 0);
$item = $model->find($id)->current();
$request = $this->getRequest();
if ($request->isGet()) {
if (is_object($item)) {
$form->populate($item->toArray());
} else {
$uri = parse_url($request->getServer('HTTP_REFERER'));
$path = trim($uri['path']);
$baseURL = $request->getBaseUrl();
$path = str_replace($baseURL, '', $path);
$bodyid = $this->_getParam('body', 'global_page_user-index-home');
$form->populate(array('path' => $path, 'bodyid' => $bodyid));
}
return;
}
if ($request->isPost() && $form->isValid($request->getPost())) {
$data = $form->getValues();
if (!is_object($item)) {
$item = $model->fetchNew();
$item->creation_date = date('Y-m-d H:i:s');
$item->setPath($form->getValue('path'));
$item->hash = md5(mt_rand(0, 999999) . mt_rand(0, 999999) . mt_rand(0, 99999), false);
}
$item->setFromArray($data);
if (!$item->save()) {
throw Exception("Invalid data");
}
$this->_forward('success', 'utility', 'core', array('smoothboxClose' => 10, 'parentRefresh' => 10, 'messages' => array('Successful.')));
}
}
示例12: test_throw
function test_throw()
{
try {
throw Exception();
} catch (Exception $exn) {
}
}
示例13: testCatchStatementHasExpectedStartLine
function testCatchStatementHasExpectedStartLine()
{
try {
throw Exception();
} catch (Exception $e) {
}
}
示例14: render
/**
* @return string
*/
public function render(\Zend\Form\ElementInterface $oElement)
{
$config = $this->getConfig();
$name = $oElement->getName();
// Check whether some options have been passed via the form element
// options
$options = $oElement->getOption('ckeditor');
if (!empty($options) && !is_array($options)) {
throw \Exception('The options should either be an array or a traversable object');
} elseif (empty($options)) {
$options = array();
}
$ckfinderLoaded = $this->getModuleManager()->getModule('CKFinderModule') !== null;
// Because zf merges arrays instead of overwriting them in the config,
// we allow a callback and use the return as the toolbar array
if (array_key_exists('toolbar', $config['ckeditor_options']) && is_callable($config['ckeditor_options']['toolbar'])) {
$toolbar = $config['ckeditor_options']['toolbar']();
if (is_array($toolbar)) {
$config['ckeditor_options']['toolbar'] = $toolbar;
}
}
// Merge the defaut edito options with the form element options
// and turn them into json
$jsonOptions = JsonFormatter::encode(array_merge($config['ckeditor_options'], $ckfinderLoaded ? $config['ckeditor_ckfinder_options'] : array(), $options), true);
$loadFunctionName = $this->getTmpLoadFunctionName();
$src = $config['src'];
return parent::render($oElement) . '<script type="text/javascript" language="javascript">' . "\n" . 'if(typeof window.ckEditorLoading == "undefined"){' . "\n" . 'window.ckEditorLoading = false;' . "\n" . 'window.ckEditorCallbacks = [];' . "\n" . '}' . "\n" . '(function() {' . "\n" . 'function ' . $loadFunctionName . '(){' . "\n" . 'CKEDITOR.replace("' . $name . '", ' . $jsonOptions . ');' . "\n" . '}' . "\n" . 'if(typeof CKEDITOR == "undefined"){' . "\n" . 'window.ckEditorCallbacks.push(' . $loadFunctionName . ');' . "\n" . 'if(!window.ckEditorLoading) {' . "\n" . 'window.ckEditorLoading = true;' . "\n" . 'var ckScript = document.createElement("script");' . "\n" . 'ckScript.type = "text/javascript";' . "\n" . 'ckScript.async = false;' . "\n" . 'ckScript.src = "' . $src . '";' . "\n" . 'var target = document.getElementsByTagName("script")[0];' . "\n" . 'target.parentNode.insertBefore(ckScript, target);' . "\n" . 'var ckEditorInterval = setInterval(function(){' . "\n" . 'if(typeof CKEDITOR != "undefined"){' . "\n" . 'clearInterval(ckEditorInterval);' . "\n" . 'for(var i in window.ckEditorCallbacks) window.ckEditorCallbacks[i]();' . "\n" . '}' . "\n" . '}, 100);' . "\n" . '}' . "\n" . '}' . "\n" . '})();' . "\n" . '</script>' . "\n";
}
示例15: put
public static function put($key, $value)
{
if (!in_array($key, self::$allowedChange)) {
throw Exception('You cannot change the value');
}
self::$configArray[$key] = $value;
}