当前位置: 首页>>代码示例>>PHP>>正文


PHP sprintf函数代码示例

本文整理汇总了PHP中sprintf函数的典型用法代码示例。如果您正苦于以下问题:PHP sprintf函数的具体用法?PHP sprintf怎么用?PHP sprintf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了sprintf函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: saveDefaultFlags

 /**
  * Saves default_billing and default_shipping flags for customer address
  *
  * @param array $addressIdList
  * @param array $extractedCustomerData
  * @return array
  */
 protected function saveDefaultFlags(array $addressIdList, array &$extractedCustomerData)
 {
     $result = [];
     $extractedCustomerData[CustomerInterface::DEFAULT_BILLING] = null;
     $extractedCustomerData[CustomerInterface::DEFAULT_SHIPPING] = null;
     foreach ($addressIdList as $addressId) {
         $scope = sprintf('address/%s', $addressId);
         $addressData = $this->_extractData($this->getRequest(), 'adminhtml_customer_address', \Magento\Customer\Api\AddressMetadataInterface::ENTITY_TYPE_ADDRESS, ['default_billing', 'default_shipping'], $scope);
         if (is_numeric($addressId)) {
             $addressData['id'] = $addressId;
         }
         // Set default billing and shipping flags to customer
         if (!empty($addressData['default_billing']) && $addressData['default_billing'] === 'true') {
             $extractedCustomerData[CustomerInterface::DEFAULT_BILLING] = $addressId;
             $addressData['default_billing'] = true;
         } else {
             $addressData['default_billing'] = false;
         }
         if (!empty($addressData['default_shipping']) && $addressData['default_shipping'] === 'true') {
             $extractedCustomerData[CustomerInterface::DEFAULT_SHIPPING] = $addressId;
             $addressData['default_shipping'] = true;
         } else {
             $addressData['default_shipping'] = false;
         }
         $result[] = $addressData;
     }
     return $result;
 }
开发者ID:nblair,项目名称:magescotch,代码行数:35,代码来源:Save.php

示例2: processAssert

 /**
  * Assert that after deleting product success message.
  *
  * @param FixtureInterface|FixtureInterface[] $product
  * @param CatalogProductIndex $productPage
  * @return void
  */
 public function processAssert($product, CatalogProductIndex $productPage)
 {
     $products = is_array($product) ? $product : [$product];
     $deleteMessage = sprintf(self::SUCCESS_DELETE_MESSAGE, count($products));
     $actualMessage = $productPage->getMessagesBlock()->getSuccessMessage();
     \PHPUnit_Framework_Assert::assertEquals($deleteMessage, $actualMessage, 'Wrong success message is displayed.' . "\nExpected: " . $deleteMessage . "\nActual: " . $actualMessage);
 }
开发者ID:andrewhowdencom,项目名称:m2onk8s,代码行数:14,代码来源:AssertProductSuccessDeleteMessage.php

示例3: assertErrorsAreTriggered

 /**
  * @param int      $expectedType     Expected triggered error type (pass one of PHP's E_* constants)
  * @param string[] $expectedMessages Expected error messages
  * @param callable $testCode         A callable that is expected to trigger the error messages
  */
 public static function assertErrorsAreTriggered($expectedType, $expectedMessages, $testCode)
 {
     if (!is_callable($testCode)) {
         throw new \InvalidArgumentException(sprintf('The code to be tested must be a valid callable ("%s" given).', gettype($testCode)));
     }
     $e = null;
     $triggeredMessages = array();
     try {
         $prevHandler = set_error_handler(function ($type, $message, $file, $line, $context) use($expectedType, &$triggeredMessages, &$prevHandler) {
             if ($expectedType !== $type) {
                 return null !== $prevHandler && call_user_func($prevHandler, $type, $message, $file, $line, $context);
             }
             $triggeredMessages[] = $message;
         });
         call_user_func($testCode);
     } catch (\Exception $e) {
     } catch (\Throwable $e) {
     }
     restore_error_handler();
     if (null !== $e) {
         throw $e;
     }
     \PHPUnit_Framework_Assert::assertCount(count($expectedMessages), $triggeredMessages);
     foreach ($triggeredMessages as $i => $message) {
         \PHPUnit_Framework_Assert::assertContains($expectedMessages[$i], $message);
     }
 }
开发者ID:unexge,项目名称:symfony,代码行数:32,代码来源:ErrorAssert.php

示例4: testChmod

 /**
  *
  */
 public function testChmod()
 {
     $cache = new FileAdapter(self::$dir, new NoneSerializer(), 0777);
     $cache->set('item', 'content');
     $perms = fileperms(self::$dir . '/' . md5('item'));
     $this->assertEquals('0777', substr(sprintf('%o', $perms), -4));
 }
开发者ID:genkgo,项目名称:cache,代码行数:10,代码来源:FileAdapterTest.php

示例5: run

 /**
  * @param ApplicationInterface $app
  *
  * @throws Exception
  */
 public function run(ApplicationInterface $app)
 {
     $this->application = $app;
     $action = $app->getRequest()->getAction();
     if ($action) {
         $actionMiddleware = new ActionMiddleware(Invokable::cast($action));
         $serviceId = $action instanceof ServiceReference ? $action->getId() : $this->computeServiceName($app->getRequest()->getUri()->getPath());
         $app->getStep('action')->plug($actionMiddleware);
     } else {
         $route = $app->getRequest()->getRoute();
         // compute service id
         $serviceId = $this->computeServiceName($route);
         // if no service matching the route has been registered,
         // try to locate a class that could be used as service
         if (!$app->getServicesFactory()->isServiceRegistered($serviceId)) {
             $actionClass = $this->resolveActionClassName($route);
             $action = $this->resolveActionFullyQualifiedName($actionClass);
             if (!$action) {
                 throw new Exception(sprintf('No callback found to map the requested route "%s"', $route), Exception::ACTION_NOT_FOUND);
             }
             $app->getServicesFactory()->registerService(['id' => $serviceId, 'class' => $action]);
         }
         // replace action by serviceId to ensure it will be fetched using the ServicesFactory
         $actionReference = new ServiceReference($serviceId);
         // wrap action to inject returned value in application
         $app->getStep('action')->plug($actionMiddleware = new ActionMiddleware($actionReference));
     }
     // store action as application parameter for further reference
     $app->setParam('runtime.action.middleware', $actionMiddleware);
     $app->setParam('runtime.action.service-id', $serviceId);
 }
开发者ID:objective-php,项目名称:application,代码行数:36,代码来源:ActionPlugger.php

示例6: configure

    public function configure()
    {
        $this->setName('phpcr:migrations:migrate');
        $this->addArgument('to', InputArgument::OPTIONAL, sprintf('Version name to migrate to, or an action: "<comment>%s</comment>"', implode('</comment>", "<comment>', $this->actions)));
        $this->setDescription('Migrate the content repository between versions');
        $this->setHelp(<<<EOT
Migrate to a specific version or perform an action.

By default it will migrate to the latest version:

    \$ %command.full_name%

You can migrate to a specific version (either in the "past" or "future"):

    \$ %command.full_name% 201504011200

Or specify an action

    \$ %command.full_name% <action>

Action can be one of:

- <comment>up</comment>: Migrate one version up
- <comment>down</comment>: Migrate one version down
- <comment>top</comment>: Migrate to the latest version
- <comment>bottom</comment>: Revert all migrations

EOT
);
    }
开发者ID:valiton-forks,项目名称:phpcr-migrations-bundle,代码行数:30,代码来源:MigrateCommand.php

示例7: parse

 /**
  * Parses a token and returns a node.
  *
  * @param  \Twig_Token $token A Twig_Token instance
  *
  * @return \Twig_NodeInterface A Twig_NodeInterface instance
  */
 public function parse(\Twig_Token $token)
 {
     $lineno = $token->getLine();
     $stream = $this->parser->getStream();
     $vars = new \Twig_Node_Expression_Array(array(), $lineno);
     $body = null;
     $count = $this->parser->getExpressionParser()->parseExpression();
     $domain = new \Twig_Node_Expression_Constant('messages', $lineno);
     if (!$stream->test(\Twig_Token::BLOCK_END_TYPE) && $stream->test('for')) {
         // {% transchoice count for "message" %}
         // {% transchoice count for message %}
         $stream->next();
         $body = $this->parser->getExpressionParser()->parseExpression();
     }
     if ($stream->test('with')) {
         // {% transchoice count with vars %}
         $stream->next();
         $vars = $this->parser->getExpressionParser()->parseExpression();
     }
     if ($stream->test('from')) {
         // {% transchoice count from "messages" %}
         $stream->next();
         $domain = $this->parser->getExpressionParser()->parseExpression();
     }
     if (null === $body) {
         // {% transchoice count %}message{% endtranschoice %}
         $stream->expect(\Twig_Token::BLOCK_END_TYPE);
         $body = $this->parser->subparse(array($this, 'decideTransChoiceFork'), true);
     }
     if (!$body instanceof \Twig_Node_Text && !$body instanceof \Twig_Node_Expression) {
         throw new \Twig_Error_Syntax(sprintf('A message must be a simple text (line %s)', $lineno), -1);
     }
     $stream->expect(\Twig_Token::BLOCK_END_TYPE);
     return new TransNode($body, $domain, $count, $vars, $lineno, $this->getTag());
 }
开发者ID:hellovic,项目名称:symfony,代码行数:42,代码来源:TransChoiceTokenParser.php

示例8: autoMagic

 /**
  * @param EveApiReadWriteInterface $data
  * @param EveApiRetrieverInterface $retrievers
  * @param EveApiPreserverInterface $preservers
  * @param int                      $interval
  *
  * @throws LogicException
  */
 public function autoMagic(EveApiReadWriteInterface $data, EveApiRetrieverInterface $retrievers, EveApiPreserverInterface $preservers, $interval)
 {
     $this->getLogger()->debug(sprintf('Starting autoMagic for %1$s/%2$s', $this->getSectionName(), $this->getApiName()));
     /**
      * Update Industry Jobs History
      */
     $class = new IndustryJobsHistory($this->getPdo(), $this->getLogger(), $this->getCsq());
     $class->autoMagic($data, $retrievers, $preservers, $interval);
     $active = $this->getActiveCharacters();
     if (0 === count($active)) {
         $this->getLogger()->info('No active characters found');
         return;
     }
     foreach ($active as $char) {
         $data->setEveApiSectionName(strtolower($this->getSectionName()))->setEveApiName($this->getApiName());
         if ($this->cacheNotExpired($this->getApiName(), $this->getSectionName(), $char['characterID'])) {
             continue;
         }
         $data->setEveApiArguments($char)->setEveApiXml();
         if (!$this->oneShot($data, $retrievers, $preservers, $interval)) {
             continue;
         }
         $this->updateCachedUntil($data->getEveApiXml(), $interval, $char['characterID']);
     }
 }
开发者ID:yapeal,项目名称:yapeal,代码行数:33,代码来源:IndustryJobs.php

示例9: getScriptingLogAction

 public function getScriptingLogAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_LOGS_SCRIPTING_LOGS);
     $this->request->defineParams(['executionId' => ['type' => 'string']]);
     $info = $this->db->GetRow("SELECT * FROM scripting_log WHERE execution_id = ? LIMIT 1", [$this->getParam('executionId')]);
     if (!$info) {
         throw new Exception('Script execution log not found');
     }
     try {
         $dbServer = DBServer::LoadByID($info['server_id']);
         if (!in_array($dbServer->status, [SERVER_STATUS::INIT, SERVER_STATUS::RUNNING])) {
             throw new Exception();
         }
     } catch (Exception $e) {
         throw new Exception('This server has been terminated and its logs are no longer available');
     }
     //Note! We should not check not-owned-farms permission here. It's approved by Igor.
     if ($dbServer->envId != $this->environment->id) {
         throw new \Scalr_Exception_InsufficientPermissions();
     }
     $logs = $dbServer->scalarizr->system->getScriptLogs($this->getParam('executionId'));
     $msg = sprintf("STDERR:\n%s \n\n STDOUT:\n%s", base64_decode($logs->stderr), base64_decode($logs->stdout));
     $msg = nl2br(htmlspecialchars($msg));
     $this->response->data(['message' => $msg]);
 }
开发者ID:mheydt,项目名称:scalr,代码行数:25,代码来源:Logs.php

示例10: addComplexType

 /**
  * Add a complex type by recursivly using all the class properties fetched via Reflection.
  *
  * @param  string $type Name of the class to be specified
  * @return string XSD Type for the given PHP type
  */
 public function addComplexType($type)
 {
     if (!class_exists($type)) {
         throw new \Zend\Soap\WSDL\Exception(sprintf('Cannot add a complex type %s that is not an object or where ' . 'class could not be found in \'DefaultComplexType\' strategy.', $type));
     }
     $dom = $this->getContext()->toDomDocument();
     $class = new \ReflectionClass($type);
     $complexType = $dom->createElement('xsd:complexType');
     $complexType->setAttribute('name', $type);
     $all = $dom->createElement('xsd:all');
     foreach ($class->getProperties() as $property) {
         if ($property->isPublic() && preg_match_all('/@var\\s+([^\\s]+)/m', $property->getDocComment(), $matches)) {
             /**
              * @todo check if 'xsd:element' must be used here (it may not be compatible with using 'complexType'
              * node for describing other classes used as attribute types for current class
              */
             $element = $dom->createElement('xsd:element');
             $element->setAttribute('name', $property->getName());
             $element->setAttribute('type', $this->getContext()->getType(trim($matches[1][0])));
             $all->appendChild($element);
         }
     }
     $complexType->appendChild($all);
     $this->getContext()->getSchema()->appendChild($complexType);
     $this->getContext()->addType($type);
     return "tns:{$type}";
 }
开发者ID:hjr3,项目名称:zf2,代码行数:33,代码来源:DefaultComplexType.php

示例11: getTable

 /**
  * Returns the DataTable associated to the ID $idTable.
  * NB: The datatable has to have been instanciated before!
  * This method will not fetch the DataTable from the DB.
  *
  * @param int $idTable
  * @throws Exception If the table can't be found
  * @return DataTable  The table
  */
 public function getTable($idTable)
 {
     if (!isset($this->tables[$idTable])) {
         throw new TableNotFoundException(sprintf("This report has been reprocessed since your last click. To see this error less often, please increase the timeout value in seconds in Settings > General Settings. (error: id %s not found).", $idTable));
     }
     return $this->tables[$idTable];
 }
开发者ID:KiwiJuicer,项目名称:handball-dachau,代码行数:16,代码来源:Manager.php

示例12: getConnectionReference

 /**
  * @param string                                                    $name
  * @param array                                                     $config
  * @param \Symfony\Component\DependencyInjection\ContainerBuilder   $container
  *
  * @return \Symfony\Component\DependencyInjection\Reference
  */
 private function getConnectionReference($name, array $config, ContainerBuilder $container)
 {
     if (isset($config['connection_id'])) {
         return new Reference($config['connection_id']);
     }
     $host = $config['host'];
     $port = $config['port'];
     $connClass = '%doctrine_cache.redis.connection.class%';
     $connId = sprintf('doctrine_cache.services.%s_redis.connection', $name);
     $connDef = new Definition($connClass);
     $connParams = array($host, $port);
     if (isset($config['timeout'])) {
         $connParams[] = $config['timeout'];
     }
     $connDef->setPublic(false);
     $connDef->addMethodCall('connect', $connParams);
     if (isset($config['password'])) {
         $password = $config['password'];
         $connDef->addMethodCall('auth', array($password));
     }
     if (isset($config['database'])) {
         $database = (int) $config['database'];
         $connDef->addMethodCall('select', array($database));
     }
     $container->setDefinition($connId, $connDef);
     return new Reference($connId);
 }
开发者ID:BusinessCookies,项目名称:CoffeeMachineProject,代码行数:34,代码来源:RedisDefinition.php

示例13: __construct

 /**
  * @param string $email
  */
 function __construct($email)
 {
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
         throw new \InvalidArgumentException(sprintf('"%s" is not a valid email', $email));
     }
     $this->email = $email;
 }
开发者ID:vivait,项目名称:customer-bundle,代码行数:10,代码来源:Email.php

示例14: setValue

 /**
  * Sets selected items (by keys).
  * @param  array
  * @return self
  */
 public function setValue($values)
 {
     if (is_scalar($values) || $values === NULL) {
         $values = (array) $values;
     } elseif (!is_array($values)) {
         throw new Nette\InvalidArgumentException(sprintf("Value must be array or NULL, %s given in field '%s'.", gettype($values), $this->name));
     }
     $flip = [];
     foreach ($values as $value) {
         if (!is_scalar($value) && !method_exists($value, '__toString')) {
             throw new Nette\InvalidArgumentException(sprintf("Values must be scalar, %s given in field '%s'.", gettype($value), $this->name));
         }
         $flip[(string) $value] = TRUE;
     }
     $values = array_keys($flip);
     if ($this->checkAllowedValues && ($diff = array_diff($values, array_keys($this->items)))) {
         $set = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) {
             return var_export($s, TRUE);
         }, array_keys($this->items))), 70, '...');
         $vals = (count($diff) > 1 ? 's' : '') . " '" . implode("', '", $diff) . "'";
         throw new Nette\InvalidArgumentException("Value{$vals} are out of allowed set [{$set}] in field '{$this->name}'.");
     }
     $this->value = $values;
     return $this;
 }
开发者ID:jjanekk,项目名称:forms,代码行数:30,代码来源:MultiChoiceControl.php

示例15: getPoint

 /**
  * @brief Get the points
  */
 function getPoint($member_srl, $from_db = false)
 {
     $member_srl = abs($member_srl);
     // Get from instance memory
     if (!$from_db && $this->pointList[$member_srl]) {
         return $this->pointList[$member_srl];
     }
     // Get from file cache
     $path = sprintf(_XE_PATH_ . 'files/member_extra_info/point/%s', getNumberingPath($member_srl));
     $cache_filename = sprintf('%s%d.cache.txt', $path, $member_srl);
     if (!$from_db && file_exists($cache_filename)) {
         return $this->pointList[$member_srl] = trim(FileHandler::readFile($cache_filename));
     }
     // Get from the DB
     $args = new stdClass();
     $args->member_srl = $member_srl;
     $output = executeQuery('point.getPoint', $args);
     if (isset($output->data->member_srl)) {
         $point = (int) $output->data->point;
         $this->pointList[$member_srl] = $point;
         if (!is_dir($path)) {
             FileHandler::makeDir($path);
         }
         FileHandler::writeFile($cache_filename, $point);
         return $point;
     }
     return 0;
 }
开发者ID:kimkucheol,项目名称:xe-core,代码行数:31,代码来源:point.model.php


注:本文中的sprintf函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。