Page Menu
Home
Phabricator
Search
Configure Global Search
Log In
Files
F14087334
D12606.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
173 KB
Referenced Files
None
Subscribers
None
D12606.diff
View Options
diff --git a/src/__phutil_library_init__.php b/src/__phutil_library_init__.php
--- a/src/__phutil_library_init__.php
+++ b/src/__phutil_library_init__.php
@@ -24,9 +24,12 @@
if (!$symbols) {
throw new PhutilMissingSymbolException(
$class_name,
- 'class or interface',
- "the class or interface '{$class_name}' is not defined in the library ".
- "map for any loaded phutil library.");
+ pht('class or interface'),
+ pht(
+ "the class or interface '%s' is not defined in the library ".
+ "map for any loaded %s library.",
+ $class_name,
+ 'phutil'));
}
} catch (PhutilMissingSymbolException $ex) {
// If there are other SPL autoloaders installed, we need to give them a
diff --git a/src/aphront/storage/connection/AphrontDatabaseConnection.php b/src/aphront/storage/connection/AphrontDatabaseConnection.php
--- a/src/aphront/storage/connection/AphrontDatabaseConnection.php
+++ b/src/aphront/storage/connection/AphrontDatabaseConnection.php
@@ -36,11 +36,11 @@
}
public function asyncQuery($raw_query) {
- throw new Exception('Async queries are not supported.');
+ throw new Exception(pht('Async queries are not supported.'));
}
public static function resolveAsyncQueries(array $conns, array $asyncs) {
- throw new Exception('Async queries are not supported.');
+ throw new Exception(pht('Async queries are not supported.'));
}
diff --git a/src/aphront/storage/connection/AphrontDatabaseTransactionState.php b/src/aphront/storage/connection/AphrontDatabaseTransactionState.php
--- a/src/aphront/storage/connection/AphrontDatabaseTransactionState.php
+++ b/src/aphront/storage/connection/AphrontDatabaseTransactionState.php
@@ -20,7 +20,10 @@
public function decreaseDepth() {
if ($this->depth == 0) {
throw new Exception(
- 'Too many calls to saveTransaction() or killTransaction()!');
+ pht(
+ 'Too many calls to %s or %s!',
+ 'saveTransaction()',
+ 'killTransaction()'));
}
return --$this->depth;
@@ -37,7 +40,10 @@
public function endReadLocking() {
if ($this->readLockLevel == 0) {
- throw new Exception('Too many calls to endReadLocking()!');
+ throw new Exception(
+ pht(
+ 'Too many calls to %s!',
+ __FUNCTION__.'()'));
}
$this->readLockLevel--;
return $this;
@@ -54,7 +60,10 @@
public function endWriteLocking() {
if ($this->writeLockLevel == 0) {
- throw new Exception('Too many calls to endWriteLocking()!');
+ throw new Exception(
+ pht(
+ 'Too many calls to %s!',
+ __FUNCTION__.'()'));
}
$this->writeLockLevel--;
return $this;
@@ -67,19 +76,29 @@
public function __destruct() {
if ($this->depth) {
throw new Exception(
- 'Process exited with an open transaction! The transaction will be '.
- 'implicitly rolled back. Calls to openTransaction() must always be '.
- 'paired with a call to saveTransaction() or killTransaction().');
+ pht(
+ 'Process exited with an open transaction! The transaction '.
+ 'will be implicitly rolled back. Calls to %s must always be '.
+ 'paired with a call to %s or %s.',
+ 'openTransaction()',
+ 'saveTransaction()',
+ 'killTransaction()'));
}
if ($this->readLockLevel) {
throw new Exception(
- 'Process exited with an open read lock! Call to beginReadLocking() '.
- 'must always be paired with a call to endReadLocking().');
+ pht(
+ 'Process exited with an open read lock! Call to %s '.
+ 'must always be paired with a call to %s.',
+ 'beginReadLocking()',
+ 'endReadLocking()'));
}
if ($this->writeLockLevel) {
throw new Exception(
- 'Process exited with an open write lock! Call to beginWriteLocking() '.
- 'must always be paired with a call to endWriteLocking().');
+ pht(
+ 'Process exited with an open write lock! Call to %s '.
+ 'must always be paired with a call to %s.',
+ 'beginWriteLocking()',
+ 'endWriteLocking()'));
}
}
diff --git a/src/aphront/storage/connection/AphrontIsolatedDatabaseConnection.php b/src/aphront/storage/connection/AphrontIsolatedDatabaseConnection.php
--- a/src/aphront/storage/connection/AphrontIsolatedDatabaseConnection.php
+++ b/src/aphront/storage/connection/AphrontIsolatedDatabaseConnection.php
@@ -82,9 +82,12 @@
if (!preg_match('/^[\s<>K]*('.$preg_keywords.')\s*/i', $raw_query)) {
throw new AphrontNotSupportedQueryException(
- "Database isolation currently only supports some queries. You are ".
- "trying to issue a query which does not begin with an allowed ".
- "keyword (".implode(', ', $keywords)."): '".$raw_query."'");
+ pht(
+ "Database isolation currently only supports some queries. You are ".
+ "trying to issue a query which does not begin with an allowed ".
+ "keyword (%s): '%s'.",
+ implode(', ', $keywords),
+ $raw_query));
}
$this->transcript[] = $raw_query;
diff --git a/src/aphront/storage/connection/mysql/AphrontBaseMySQLDatabaseConnection.php b/src/aphront/storage/connection/mysql/AphrontBaseMySQLDatabaseConnection.php
--- a/src/aphront/storage/connection/mysql/AphrontBaseMySQLDatabaseConnection.php
+++ b/src/aphront/storage/connection/mysql/AphrontBaseMySQLDatabaseConnection.php
@@ -101,7 +101,7 @@
if ($retries && $ex->getCode() == 2003) {
$class = get_class($ex);
$message = $ex->getMessage();
- phlog("Retrying ({$retries}) after {$class}: {$message}");
+ phlog(pht('Retrying (%d) after %s: %s', $retries, $class, $message));
} else {
$profiler->endServiceCall($call_id, array());
throw $ex;
@@ -140,7 +140,7 @@
$result = array();
$res = $this->lastResult;
if ($res == null) {
- throw new Exception('No query result to fetch from!');
+ throw new Exception(pht('No query result to fetch from!'));
}
while (($row = $this->fetchAssoc($res))) {
$result[] = $row;
@@ -266,7 +266,7 @@
protected function throwQueryException($connection) {
if ($this->nextError) {
$errno = $this->nextError;
- $error = 'Simulated error.';
+ $error = pht('Simulated error.');
$this->nextError = null;
} else {
$errno = $this->getErrorCode($connection);
@@ -282,8 +282,11 @@
case 2013: // Connection Dropped
throw new AphrontConnectionLostQueryException($exmsg);
case 2006: // Gone Away
- $more = "This error may occur if your MySQL 'wait_timeout' ".
- "or 'max_allowed_packet' configuration values are set too low.";
+ $more = pht(
+ "This error may occur if your MySQL '%s' or '%s' ".
+ "configuration values are set too low.",
+ 'wait_timeout',
+ 'max_allowed_packet');
throw new AphrontConnectionLostQueryException("{$exmsg}\n\n{$more}");
case 1213: // Deadlock
case 1205: // Lock wait timeout exceeded
diff --git a/src/aphront/storage/connection/mysql/AphrontMySQLDatabaseConnection.php b/src/aphront/storage/connection/mysql/AphrontMySQLDatabaseConnection.php
--- a/src/aphront/storage/connection/mysql/AphrontMySQLDatabaseConnection.php
+++ b/src/aphront/storage/connection/mysql/AphrontMySQLDatabaseConnection.php
@@ -31,8 +31,9 @@
// installed, which has bitten me on three separate occasions. Make sure
// such failures are explicit and loud.
throw new Exception(
- 'About to call mysql_connect(), but the PHP MySQL extension is not '.
- 'available!');
+ pht(
+ 'About to call %s, but the PHP MySQL extension is not available!',
+ 'mysql_connect()'));
}
$user = $this->getConfiguration('user');
@@ -61,8 +62,13 @@
$errno = mysql_errno();
$error = mysql_error();
throw new AphrontConnectionQueryException(
- "Attempt to connect to {$user}@{$host} failed with error ".
- "#{$errno}: {$error}.", $errno);
+ pht(
+ 'Attempt to connect to %s@%s failed with error #%d: %s.',
+ $user,
+ $host,
+ $errno,
+ $error),
+ $errno);
}
if ($database !== null) {
@@ -117,7 +123,8 @@
}
if (!$processed_all) {
- throw new Exception('There are some results left in the result set.');
+ throw new Exception(
+ pht('There are some results left in the result set.'));
}
return $results;
diff --git a/src/aphront/storage/connection/mysql/AphrontMySQLiDatabaseConnection.php b/src/aphront/storage/connection/mysql/AphrontMySQLiDatabaseConnection.php
--- a/src/aphront/storage/connection/mysql/AphrontMySQLiDatabaseConnection.php
+++ b/src/aphront/storage/connection/mysql/AphrontMySQLiDatabaseConnection.php
@@ -29,9 +29,9 @@
protected function connect() {
if (!class_exists('mysqli', false)) {
- throw new Exception(
- 'About to call new mysqli(), but the PHP MySQLi extension is not '.
- 'available!');
+ throw new Exception(pht(
+ 'About to call new %s, but the PHP MySQLi extension is not available!',
+ 'mysqli()'));
}
$user = $this->getConfiguration('user');
@@ -70,8 +70,13 @@
if ($errno) {
$error = $conn->connect_error;
throw new AphrontConnectionQueryException(
- "Attempt to connect to {$user}@{$host} failed with error ".
- "#{$errno}: {$error}.", $errno);
+ pht(
+ 'Attempt to connect to %s@%s failed with error #%d: %s.',
+ $user,
+ $host,
+ $errno,
+ $error),
+ $errno);
}
$ok = @$conn->set_charset('utf8mb4');
@@ -111,7 +116,8 @@
}
if ($conn->more_results()) {
- throw new Exception('There are some results left in the result set.');
+ throw new Exception(
+ pht('There are some results left in the result set.'));
}
return $results;
diff --git a/src/aphront/storage/exception/AphrontParameterQueryException.php b/src/aphront/storage/exception/AphrontParameterQueryException.php
--- a/src/aphront/storage/exception/AphrontParameterQueryException.php
+++ b/src/aphront/storage/exception/AphrontParameterQueryException.php
@@ -5,7 +5,7 @@
private $query;
public function __construct($query, $message) {
- parent::__construct($message.' Query: '.$query);
+ parent::__construct(pht('%s Query: %s', $message, $query));
$this->query = $query;
}
diff --git a/src/aphront/writeguard/AphrontWriteGuard.php b/src/aphront/writeguard/AphrontWriteGuard.php
--- a/src/aphront/writeguard/AphrontWriteGuard.php
+++ b/src/aphront/writeguard/AphrontWriteGuard.php
@@ -65,14 +65,18 @@
public function __construct($callback) {
if (self::$instance) {
throw new Exception(
- 'An AphrontWriteGuard already exists. Dispose of the previous guard '.
- 'before creating a new one.');
+ pht(
+ 'An %s already exists. Dispose of the previous guard '.
+ 'before creating a new one.',
+ __CLASS__));
}
if (self::$allowUnguardedWrites) {
throw new Exception(
- 'An AphrontWriteGuard is being created in a context which permits '.
- 'unguarded writes unconditionally. This is not allowed and indicates '.
- 'a serious error.');
+ pht(
+ 'An %s is being created in a context which permits '.
+ 'unguarded writes unconditionally. This is not allowed and '.
+ 'indicates a serious error.',
+ __CLASS__));
}
if (!self::$abruptExitlistenerIsInstalled) {
self::$abruptExitlistenerIsInstalled = true;
@@ -93,14 +97,17 @@
*/
public function dispose() {
if (!self::$instance) {
- throw new Exception(
- 'Attempting to dispose of write guard, but no write guard is active!');
+ throw new Exception(pht(
+ 'Attempting to dispose of write guard, but no write guard is active!'));
}
if ($this->allowDepth > 0) {
throw new Exception(
- 'Imbalanced AphrontWriteGuard: more beginUnguardedWrites() calls than '.
- 'endUnguardedWrites() calls.');
+ pht(
+ 'Imbalanced %s: more % calls than %s calls.',
+ __CLASS__,
+ 'beginUnguardedWrites()',
+ 'endUnguardedWrites()'));
}
self::$instance = null;
}
@@ -162,8 +169,9 @@
if (!self::$instance) {
if (!self::$allowUnguardedWrites) {
throw new Exception(
- 'Unguarded write! There must be an active AphrontWriteGuard to '.
- 'perform writes.');
+ pht(
+ 'Unguarded write! There must be an active %s to perform writes.',
+ __CLASS__));
} else {
// Unguarded writes are being allowed unconditionally.
return;
@@ -237,8 +245,11 @@
}
if (self::$instance->allowDepth <= 0) {
throw new Exception(
- 'Imbalanced AphrontWriteGuard: more endUnguardedWrites() calls than '.
- 'beginUnguardedWrites() calls.');
+ pht(
+ 'Imbalanced %s: more %s calls than %s calls.',
+ __CLASS__,
+ 'endUnguardedWrites()',
+ 'beginUnguardedWrites()'));
}
self::$instance->allowDepth--;
}
@@ -259,9 +270,12 @@
public static function allowDangerousUnguardedWrites($allow) {
if (self::$instance) {
throw new Exception(
- 'You can not unconditionally disable AphrontWriteGuard by calling '.
- 'allowDangerousUnguardedWrites() while a write guard is active. Use '.
- 'beginUnguardedWrites() to temporarily allow unguarded writes.');
+ pht(
+ 'You can not unconditionally disable %s by calling %s while a write '.
+ 'guard is active. Use %s to temporarily allow unguarded writes.',
+ __CLASS__,
+ __FUNCTION__.'()',
+ 'beginUnguardedWrites()'));
}
self::$allowUnguardedWrites = true;
}
@@ -278,9 +292,13 @@
public function __destruct() {
if (isset(self::$instance)) {
throw new Exception(
- 'AphrontWriteGuard was not properly disposed of! Call dispose() on '.
- 'every AphrontWriteGuard object you instantiate or use phutil_exit() '.
- 'to exit abruptly while debugging.');
+ pht(
+ '%s was not properly disposed of! Call %s on every %s object you '.
+ 'instantiate or use %s to exit abruptly while debugging.',
+ __CLASS__,
+ 'dispose()',
+ __CLASS__,
+ 'phutil_exit()'));
}
}
diff --git a/src/auth/PhutilGoogleAuthAdapter.php b/src/auth/PhutilGoogleAuthAdapter.php
--- a/src/auth/PhutilGoogleAuthAdapter.php
+++ b/src/auth/PhutilGoogleAuthAdapter.php
@@ -139,9 +139,9 @@
if ($domain == 'usageLimits' && $reason == 'accessNotConfigured') {
throw new PhutilAuthConfigurationException(
pht(
- 'Google returned an "accessNotConfigured" error. This usually means '.
- 'you need to enable the "Google+ API" in your Google Cloud Console, '.
- 'under "APIs".'.
+ 'Google returned an "%s" error. This usually means you need to '.
+ 'enable the "Google+ API" in your Google Cloud Console, under '.
+ '"APIs".'.
"\n\n".
'Around March 2014, Google made some API changes which require this '.
'configuration adjustment.'.
@@ -155,13 +155,14 @@
'"Credentials". The Application ID this install is using is "%s".'.
"\n\n".
'(If you are unable to log into Phabricator, you can use '.
- '"bin/auth recover" to recover access to an administrator '.
- 'account.)'.
+ '"%s" to recover access to an administrator account.)'.
"\n\n".
'Full HTTP Response'.
"\n\n%s",
+ 'accessNotConfigured',
'https://console.developers.google.com/',
$this->getClientID(),
+ 'bin/auth recover',
$raw_body));
}
}
diff --git a/src/auth/PhutilJIRAAuthAdapter.php b/src/auth/PhutilJIRAAuthAdapter.php
--- a/src/auth/PhutilJIRAAuthAdapter.php
+++ b/src/auth/PhutilJIRAAuthAdapter.php
@@ -111,18 +111,18 @@
$res = openssl_pkey_new($config);
if (!$res) {
- throw new Exception('openssl_pkey_new() failed!');
+ throw new Exception(pht('%s failed!', 'openssl_pkey_new()'));
}
$private_key = null;
$ok = openssl_pkey_export($res, $private_key);
if (!$ok) {
- throw new Exception('openssl_pkey_export() failed!');
+ throw new Exception(pht('%s failed!', 'openssl_pkey_export()'));
}
$public_key = openssl_pkey_get_details($res);
if (!$ok || empty($public_key['key'])) {
- throw new Exception('openssl_pkey_get_details() failed!');
+ throw new Exception(pht('%s failed!', 'openssl_pkey_get_details()'));
}
$public_key = $public_key['key'];
diff --git a/src/auth/PhutilLDAPAuthAdapter.php b/src/auth/PhutilLDAPAuthAdapter.php
--- a/src/auth/PhutilLDAPAuthAdapter.php
+++ b/src/auth/PhutilLDAPAuthAdapter.php
@@ -315,7 +315,7 @@
if (!$conn) {
throw new Exception(
- "Unable to connect to LDAP server ({$host}:{$port}).");
+ pht('Unable to connect to LDAP server (%s:%d).', $host, $port));
}
$options = array(
diff --git a/src/auth/PhutilOAuth1AuthAdapter.php b/src/auth/PhutilOAuth1AuthAdapter.php
--- a/src/auth/PhutilOAuth1AuthAdapter.php
+++ b/src/auth/PhutilOAuth1AuthAdapter.php
@@ -139,7 +139,7 @@
$confirmed = idx($data, 'oauth_callback_confirmed');
if ($confirmed !== 'true') {
throw new Exception(
- "Expected 'oauth_callback_confirmed' to be 'true'!");
+ pht("Expected '%s' to be '%s'!", 'oauth_callback_confirmed', 'true'));
}
$this->readTokenAndTokenSecret($data);
@@ -154,10 +154,10 @@
$this->willFinishOAuthHandshake();
if (!$this->getToken()) {
- throw new Exception('Expected token to finish OAuth handshake!');
+ throw new Exception(pht('Expected token to finish OAuth handshake!'));
}
if (!$this->getVerifier()) {
- throw new Exception('Expected verifier to finish OAuth handshake!');
+ throw new Exception(pht('Expected verifier to finish OAuth handshake!'));
}
$validate_uri = $this->getValidateTokenURI();
@@ -176,12 +176,13 @@
private function readTokenAndTokenSecret(array $data) {
$token = idx($data, 'oauth_token');
if (!$token) {
- throw new Exception("Expected 'oauth_token' in response!");
+ throw new Exception(pht("Expected '%s' in response!", 'oauth_token'));
}
$token_secret = idx($data, 'oauth_token_secret');
if (!$token_secret) {
- throw new Exception("Expected 'oauth_token_secret' in response!");
+ throw new Exception(
+ pht("Expected '%s' in response!", 'oauth_token_secret'));
}
$this->setToken($token);
diff --git a/src/auth/PhutilOAuthAuthAdapter.php b/src/auth/PhutilOAuthAuthAdapter.php
--- a/src/auth/PhutilOAuthAuthAdapter.php
+++ b/src/auth/PhutilOAuthAuthAdapter.php
@@ -152,7 +152,7 @@
$code = $this->getCode();
if (!$code) {
throw new Exception(
- 'Call setCode() before accessing adapter information.');
+ pht('Call %s before accessing adapter information.', 'setCode()'));
}
$params = array(
@@ -192,7 +192,7 @@
}
if (isset($data['error'])) {
- throw new Exception('Access token error: '.$data['error']);
+ throw new Exception(pht('Access token error: %s', $data['error']));
}
return $data;
@@ -213,7 +213,7 @@
if (empty($data['access_token']) &&
empty($data['error'])) {
throw new Exception(
- "Failed to decode OAuth access token response: {$body}");
+ pht('Failed to decode OAuth access token response: %s', $body));
}
return $data;
diff --git a/src/auth/PhutilPersonaAuthAdapter.php b/src/auth/PhutilPersonaAuthAdapter.php
--- a/src/auth/PhutilPersonaAuthAdapter.php
+++ b/src/auth/PhutilPersonaAuthAdapter.php
@@ -55,12 +55,12 @@
$audience = idx($response, 'audience');
if ($audience != $this->audience) {
- throw new Exception("Mismatched Persona audience: {$audience}");
+ throw new Exception(pht('Mismatched Persona audience: %s', $audience));
}
if (idx($response, 'status') !== 'okay') {
$reason = idx($response, 'reason', 'Unknown');
- throw new Exception("Persona login failed: {$reason}");
+ throw new Exception(pht('Persona login failed: %s', $reason));
}
$this->accountData = $response;
diff --git a/src/cache/PhutilDirectoryKeyValueCache.php b/src/cache/PhutilDirectoryKeyValueCache.php
--- a/src/cache/PhutilDirectoryKeyValueCache.php
+++ b/src/cache/PhutilDirectoryKeyValueCache.php
@@ -170,7 +170,9 @@
private function getCacheDirectory() {
if (!$this->cacheDirectory) {
throw new Exception(
- 'Call setCacheDirectory() before using a directory cache!');
+ pht(
+ 'Call %s before using a directory cache!',
+ 'setCacheDirectory()'));
}
return $this->cacheDirectory;
}
@@ -199,8 +201,10 @@
// Use of "_" is reserved for converting ":".
if (!preg_match('@^[a-zA-Z0-9/:-]+$@', $key)) {
throw new Exception(
- "Invalid key '{$key}': directory caches may only contain letters, ".
- "numbers, hyphen, colon and slash.");
+ pht(
+ "Invalid key '%s': directory caches may only contain letters, ".
+ "numbers, hyphen, colon and slash.",
+ $key));
}
}
}
@@ -211,7 +215,10 @@
*/
private function lockCache($wait = 0) {
if ($this->lock) {
- throw new Exception('Trying to lockCache() with a lock!');
+ throw new Exception(
+ pht(
+ 'Trying to %s with a lock!',
+ __FUNCTION__.'()'));
}
if (!Filesystem::pathExists($this->getCacheDirectory())) {
@@ -231,7 +238,10 @@
private function unlockCache() {
if (!$this->lock) {
throw new Exception(
- 'Call lockCache() before unlockCache()!');
+ pht(
+ 'Call %s before %s!',
+ 'lockCache()',
+ __FUNCTION__.'()'));
}
$this->lock->unlock();
diff --git a/src/cache/PhutilKeyValueCacheNamespace.php b/src/cache/PhutilKeyValueCacheNamespace.php
--- a/src/cache/PhutilKeyValueCacheNamespace.php
+++ b/src/cache/PhutilKeyValueCacheNamespace.php
@@ -6,7 +6,7 @@
public function setNamespace($namespace) {
if (strpos($namespace, ':') !== false) {
- throw new Exception('Namespace can\'t contain colons');
+ throw new Exception(pht("Namespace can't contain colons."));
}
$this->namespace = $namespace.':';
@@ -38,7 +38,7 @@
private function prefixKeys(array $keys) {
if ($this->namespace == null) {
- throw new Exception('Namespace not set');
+ throw new Exception(pht('Namespace not set.'));
}
$prefixed_keys = array();
@@ -51,7 +51,7 @@
private function unprefixKeys(array $keys) {
if ($this->namespace == null) {
- throw new Exception('Namespace not set');
+ throw new Exception(pht('Namespace not set.'));
}
$unprefixed_keys = array();
diff --git a/src/cache/PhutilMemcacheKeyValueCache.php b/src/cache/PhutilMemcacheKeyValueCache.php
--- a/src/cache/PhutilMemcacheKeyValueCache.php
+++ b/src/cache/PhutilMemcacheKeyValueCache.php
@@ -114,7 +114,10 @@
$n = count($this->servers);
if (!$n) {
- throw new Exception('Call setServers() before using Memcache!');
+ throw new Exception(
+ pht(
+ 'Call %s before using Memcache!',
+ 'setServers()'));
}
foreach ($keys as $key) {
@@ -139,7 +142,10 @@
if (!$conn) {
throw new Exception(
- "Unable to connect to memcache server ({$host}@{$port})!");
+ pht(
+ 'Unable to connect to memcache server (%s:%d)!',
+ $host,
+ $port));
}
$this->connections[$server] = $conn;
diff --git a/src/cache/PhutilOnDiskKeyValueCache.php b/src/cache/PhutilOnDiskKeyValueCache.php
--- a/src/cache/PhutilOnDiskKeyValueCache.php
+++ b/src/cache/PhutilOnDiskKeyValueCache.php
@@ -133,7 +133,10 @@
*/
private function loadCache($hold_lock) {
if ($this->lock) {
- throw new Exception('Trying to loadCache() with a lock!');
+ throw new Exception(
+ pht(
+ 'Trying to %s with a lock!',
+ __FUNCTION__.'()'));
}
$lock = PhutilFileLock::newForPath($this->getCacheFile().'.lock');
@@ -175,7 +178,10 @@
private function saveCache() {
if (!$this->lock) {
throw new Exception(
- 'Call loadCache($hold_lock=true) before saveCache()!');
+ pht(
+ 'Call %s before %s!',
+ 'loadCache($hold_lock=true)',
+ __FUNCTION__.'()'));
}
// We're holding a lock so we're safe to do a write to a well-known file.
@@ -195,7 +201,10 @@
*/
private function getCacheFile() {
if (!$this->cacheFile) {
- throw new Exception('Call setCacheFile() before using a disk cache!');
+ throw new Exception(
+ pht(
+ 'Call %s before using a disk cache!',
+ 'setCacheFile()'));
}
return $this->cacheFile;
}
diff --git a/src/cache/__tests__/PhutilKeyValueCacheTestCase.php b/src/cache/__tests__/PhutilKeyValueCacheTestCase.php
--- a/src/cache/__tests__/PhutilKeyValueCacheTestCase.php
+++ b/src/cache/__tests__/PhutilKeyValueCacheTestCase.php
@@ -49,7 +49,7 @@
public function testAPCCache() {
$cache = new PhutilAPCKeyValueCache();
if (!$cache->isAvailable()) {
- $this->assertSkipped('Cache not available.');
+ $this->assertSkipped(pht('Cache not available.'));
}
$this->doCacheTest($cache);
}
diff --git a/src/channel/PhutilChannel.php b/src/channel/PhutilChannel.php
--- a/src/channel/PhutilChannel.php
+++ b/src/channel/PhutilChannel.php
@@ -72,7 +72,10 @@
*/
public function write($bytes) {
if (!is_scalar($bytes)) {
- throw new Exception('PhutilChannel->write() may only write strings!');
+ throw new Exception(
+ pht(
+ '%s may only write strings!',
+ __METHOD__.'()'));
}
$this->obuf->append($bytes);
@@ -414,7 +417,7 @@
while (!$this->isWriteBufferEmpty()) {
self::waitForAny(array($this));
if (!$this->update()) {
- throw new Exception('Channel closed while flushing output!');
+ throw new Exception(pht('Channel closed while flushing output!'));
}
}
return $this;
diff --git a/src/channel/PhutilChannelChannel.php b/src/channel/PhutilChannelChannel.php
--- a/src/channel/PhutilChannelChannel.php
+++ b/src/channel/PhutilChannelChannel.php
@@ -100,8 +100,13 @@
// protected.
throw new Exception(
- 'Do not call readBytes() or writeBytes() directly on a '.
- 'PhutilChannelChannel. Instead, call read() or write().');
+ pht(
+ 'Do not call %s or %s directly on a %s. Instead, call %s or %s.',
+ 'readBytes()',
+ 'writeBytes()',
+ __CLASS__,
+ 'read()',
+ 'write()'));
}
}
diff --git a/src/channel/PhutilExecChannel.php b/src/channel/PhutilExecChannel.php
--- a/src/channel/PhutilExecChannel.php
+++ b/src/channel/PhutilExecChannel.php
@@ -97,7 +97,7 @@
call_user_func($this->stderrHandler, $this, $stderr);
} else {
throw new Exception(
- "Unexpected output to stderr on exec channel: {$stderr}");
+ pht('Unexpected output to stderr on exec channel: %s', $stderr));
}
}
@@ -113,7 +113,7 @@
}
protected function writeBytes($bytes) {
- throw new Exception('ExecFuture can not write bytes directly!');
+ throw new Exception(pht('%s can not write bytes directly!', 'ExecFuture'));
}
protected function getReadSockets() {
diff --git a/src/channel/PhutilPHPObjectProtocolChannel.php b/src/channel/PhutilPHPObjectProtocolChannel.php
--- a/src/channel/PhutilPHPObjectProtocolChannel.php
+++ b/src/channel/PhutilPHPObjectProtocolChannel.php
@@ -73,7 +73,7 @@
$obj = @unserialize($data);
if ($obj === false) {
- throw new Exception("Failed to unserialize object: {$data}");
+ throw new Exception(pht('Failed to unserialize object: %s', $data));
} else {
$objects[] = $obj;
}
diff --git a/src/channel/PhutilProtocolChannel.php b/src/channel/PhutilProtocolChannel.php
--- a/src/channel/PhutilProtocolChannel.php
+++ b/src/channel/PhutilProtocolChannel.php
@@ -133,7 +133,7 @@
self::waitForAny(array($this));
}
- throw new Exception('Channel closed while waiting for message!');
+ throw new Exception(pht('Channel closed while waiting for message!'));
}
}
diff --git a/src/channel/PhutilSocketChannel.php b/src/channel/PhutilSocketChannel.php
--- a/src/channel/PhutilSocketChannel.php
+++ b/src/channel/PhutilSocketChannel.php
@@ -48,7 +48,7 @@
}
$ok = stream_set_blocking($socket, false);
if (!$ok) {
- throw new Exception('Failed to set socket nonblocking!');
+ throw new Exception(pht('Failed to set socket nonblocking!'));
}
}
@@ -80,7 +80,7 @@
$domain = phutil_is_windows() ? STREAM_PF_INET : STREAM_PF_UNIX;
$pair = stream_socket_pair($domain, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
if (!$pair) {
- throw new Exception('stream_socket_pair() failed!');
+ throw new Exception(pht('%s failed!', 'stream_socket_pair()'));
}
$x = new PhutilSocketChannel($pair[0]);
diff --git a/src/channel/__tests__/PhutilJSONProtocolChannelTestCase.php b/src/channel/__tests__/PhutilJSONProtocolChannelTestCase.php
--- a/src/channel/__tests__/PhutilJSONProtocolChannelTestCase.php
+++ b/src/channel/__tests__/PhutilJSONProtocolChannelTestCase.php
@@ -20,7 +20,7 @@
$this->assertEqual(
$dict,
$result,
- 'Values are identical.');
+ pht('Values are identical.'));
}
}
diff --git a/src/channel/__tests__/PhutilPHPObjectProtocolChannelTestCase.php b/src/channel/__tests__/PhutilPHPObjectProtocolChannelTestCase.php
--- a/src/channel/__tests__/PhutilPHPObjectProtocolChannelTestCase.php
+++ b/src/channel/__tests__/PhutilPHPObjectProtocolChannelTestCase.php
@@ -17,11 +17,11 @@
$this->assertTrue(
(array)$object === (array)$result,
- 'Values are identical.');
+ pht('Values are identical.'));
$this->assertFalse(
$object === $result,
- 'Objects are not the same.');
+ pht('Objects are not the same.'));
}
public function testCloseSocketWriteChannel() {
@@ -41,7 +41,7 @@
// returning, which would be hard to diagnose. Since the current
// implementation shuts down the entire channel, just test for that.
- $this->assertFalse($xp->update(), 'Expected channel to close.');
+ $this->assertFalse($xp->update(), pht('Expected channel to close.'));
}
public function testCloseExecWriteChannel() {
diff --git a/src/conduit/ConduitClient.php b/src/conduit/ConduitClient.php
--- a/src/conduit/ConduitClient.php
+++ b/src/conduit/ConduitClient.php
@@ -24,7 +24,8 @@
public function __construct($uri) {
$this->uri = new PhutilURI($uri);
if (!strlen($this->uri->getDomain())) {
- throw new Exception("Conduit URI '{$uri}' must include a valid host.");
+ throw new Exception(
+ pht("Conduit URI '%s' must include a valid host.", $uri));
}
$this->host = $this->uri->getDomain();
}
@@ -193,7 +194,8 @@
$signature,
$this->privateKey->openEnvelope());
if (!$result) {
- throw new Exception('Unable to sign Conduit request with signing key.');
+ throw new Exception(
+ pht('Unable to sign Conduit request with signing key.'));
}
return self::SIGNATURE_CONSIGN_1.base64_encode($signature);
@@ -212,8 +214,9 @@
default:
throw new Exception(
pht(
- 'Unable to verify request signature, specified "auth.type" '.
+ 'Unable to verify request signature, specified "%s" '.
'("%s") is unknown.',
+ 'auth.type',
$auth_type));
}
@@ -221,16 +224,18 @@
if (!strlen($public_key)) {
throw new Exception(
pht(
- 'Unable to verify request signature, no "auth.key" present in '.
- 'request protocol information.'));
+ 'Unable to verify request signature, no "%s" present in '.
+ 'request protocol information.',
+ 'auth.key'));
}
$signature = idx($meta, 'auth.signature');
if (!strlen($signature)) {
throw new Exception(
pht(
- 'Unable to verify request signature, no "auth.signature" present '.
- 'in request protocol information.'));
+ 'Unable to verify request signature, no "%s" present '.
+ 'in request protocol information.',
+ 'auth.signature'));
}
$prefix = self::SIGNATURE_CONSIGN_1;
@@ -270,8 +275,7 @@
if (strlen($err)) {
throw new Exception(
pht(
- 'OpenSSL encountered an error verifying the request signature: '.
- '%s',
+ 'OpenSSL encountered an error verifying the request signature: %s',
$err));
} else {
throw new Exception(
diff --git a/src/console/PhutilConsole.php b/src/console/PhutilConsole.php
--- a/src/console/PhutilConsole.php
+++ b/src/console/PhutilConsole.php
@@ -215,7 +215,10 @@
} else if ($this->messages) {
$message = array_shift($this->messages);
} else {
- throw new Exception('waitForMessage() called with no messages!');
+ throw new Exception(
+ pht(
+ '%s called with no messages!',
+ __FUNCTION__.'()'));
}
return $message;
@@ -232,7 +235,7 @@
private function enableMessageType($type) {
if ($this->disabledTypes[$type] == 0) {
- throw new Exception("Message type '{$type}' is already enabled!");
+ throw new Exception(pht("Message type '%s' is already enabled!", $type));
}
$this->disabledTypes[$type] -= 1;
return $this;
diff --git a/src/console/PhutilConsoleProgressBar.php b/src/console/PhutilConsoleProgressBar.php
--- a/src/console/PhutilConsoleProgressBar.php
+++ b/src/console/PhutilConsoleProgressBar.php
@@ -153,7 +153,7 @@
if ($this->drawn) {
$this->eraseLine();
if ($clean_exit) {
- $console->writeErr("%s\n", 'Done.');
+ $console->writeErr("%s\n", pht('Done.'));
}
}
$this->finished = true;
diff --git a/src/console/PhutilConsoleStdinNotInteractiveException.php b/src/console/PhutilConsoleStdinNotInteractiveException.php
--- a/src/console/PhutilConsoleStdinNotInteractiveException.php
+++ b/src/console/PhutilConsoleStdinNotInteractiveException.php
@@ -10,8 +10,9 @@
public function __construct() {
parent::__construct(
- 'The program is attempting to read user input, but stdin is being piped '.
- 'from some other source (not a TTY).');
+ pht(
+ 'The program is attempting to read user input, but stdin is being '.
+ 'piped from some other source (not a TTY).'));
}
}
diff --git a/src/console/PhutilInteractiveEditor.php b/src/console/PhutilInteractiveEditor.php
--- a/src/console/PhutilInteractiveEditor.php
+++ b/src/console/PhutilInteractiveEditor.php
@@ -78,7 +78,7 @@
if ($err) {
Filesystem::remove($tmp);
- throw new Exception("Editor exited with an error code (#{$err}).");
+ throw new Exception(pht('Editor exited with an error code (#%d).', $err));
}
try {
@@ -171,7 +171,7 @@
/**
- * Get the current document name. See setName() for details.
+ * Get the current document name. See @{method:setName} for details.
*
* @return string Current document name.
*
@@ -275,8 +275,10 @@
}
throw new Exception(
- 'Unable to launch an interactive text editor. Set the EDITOR '.
- 'environment variable to an appropriate editor.');
+ pht(
+ 'Unable to launch an interactive text editor. Set the %s '.
+ 'environment variable to an appropriate editor.',
+ 'EDITOR'));
}
}
diff --git a/src/daemon/PhutilDaemon.php b/src/daemon/PhutilDaemon.php
--- a/src/daemon/PhutilDaemon.php
+++ b/src/daemon/PhutilDaemon.php
@@ -103,7 +103,12 @@
if ($this->traceMemory) {
$memuse = number_format(memory_get_usage() / 1024, 1);
$daemon = get_class($this);
- fprintf(STDERR, '%s', "<RAMS> {$daemon} Memory Usage: {$memuse} KB\n");
+ fprintf(
+ STDERR,
+ "<%s> %s %s\n",
+ '<RAMS>',
+ $daemon,
+ pht('Memory Usage: %d KB', $memuse));
}
}
@@ -226,7 +231,7 @@
final protected function log($message) {
if ($this->verbose) {
$daemon = get_class($this);
- fprintf(STDERR, '%s', "<VERB> {$daemon} {$message}\n");
+ fprintf(STDERR, "<%s> %s %s\n", '<VERB>', $daemon, $message);
}
}
diff --git a/src/daemon/PhutilDaemonHandle.php b/src/daemon/PhutilDaemonHandle.php
--- a/src/daemon/PhutilDaemonHandle.php
+++ b/src/daemon/PhutilDaemonHandle.php
@@ -274,7 +274,7 @@
private function updateMemory() {
if ($this->traceMemory) {
$memuse = number_format(memory_get_usage() / 1024, 1);
- $this->logMessage('RAMS', 'Overseer Memory Usage: '.$memuse.' KB');
+ $this->logMessage('RAMS', pht('Overseer Memory Usage: %d KB', $memuse));
}
}
@@ -399,9 +399,12 @@
public function didReceiveTerminalSignal($signo) {
$signame = phutil_get_signal_name($signo);
if ($signame) {
- $sigmsg = "Shutting down in response to signal {$signo} ({$signame}).";
+ $sigmsg = pht(
+ 'Shutting down in response to signal %s (%s).',
+ $signo,
+ $signame);
} else {
- $sigmsg = "Shutting down in response to signal {$signo}.";
+ $sigmsg = pht('Shutting down in response to signal %s.', $signo);
}
$this->logMessage('EXIT', $sigmsg, $signo);
diff --git a/src/daemon/PhutilDaemonOverseer.php b/src/daemon/PhutilDaemonOverseer.php
--- a/src/daemon/PhutilDaemonOverseer.php
+++ b/src/daemon/PhutilDaemonOverseer.php
@@ -40,18 +40,19 @@
array(
array(
'name' => 'trace-memory',
- 'help' => 'Enable debug memory tracing.',
+ 'help' => pht('Enable debug memory tracing.'),
),
array(
'name' => 'verbose',
- 'help' => 'Enable verbose activity logging.',
+ 'help' => pht('Enable verbose activity logging.'),
),
array(
'name' => 'label',
'short' => 'l',
'param' => 'label',
'help' => pht(
- 'Optional process label. Makes "ps" nicer, no behavioral effects.'),
+ 'Optional process label. Makes "%s" nicer, no behavioral effects.',
+ 'ps'),
),
));
$argv = array();
@@ -95,7 +96,7 @@
if (self::$instance) {
throw new Exception(
- 'You may not instantiate more than one Overseer per process.');
+ pht('You may not instantiate more than one Overseer per process.'));
}
self::$instance = $this;
@@ -110,8 +111,10 @@
Filesystem::assertWritable($dir);
} catch (Exception $ex) {
throw new Exception(
- "Specified daemon PID directory ('{$dir}') does not exist or is ".
- "not writable by the daemon user!");
+ pht(
+ "Specified daemon PID directory ('%s') does not exist or is ".
+ "not writable by the daemon user!",
+ $dir));
}
}
@@ -136,7 +139,7 @@
$pid = pcntl_fork();
if ($pid === -1) {
- throw new Exception('Unable to fork!');
+ throw new Exception(pht('Unable to fork!'));
} else if ($pid) {
exit(0);
}
diff --git a/src/daemon/torture/PhutilHighIntensityIntervalDaemon.php b/src/daemon/torture/PhutilHighIntensityIntervalDaemon.php
--- a/src/daemon/torture/PhutilHighIntensityIntervalDaemon.php
+++ b/src/daemon/torture/PhutilHighIntensityIntervalDaemon.php
@@ -3,7 +3,6 @@
/**
* Daemon which is very busy every other minute. This will cause it to
* autoscale up and down.
- *
*/
final class PhutilHighIntensityIntervalDaemon extends PhutilTortureTestDaemon {
@@ -12,10 +11,10 @@
$m = (int)date('i');
if ($m % 2) {
$this->willBeginWork();
- $this->log('Busy.');
+ $this->log(pht('Busy.'));
} else {
$this->willBeginIdle();
- $this->log('Idle.');
+ $this->log(pht('Idle.'));
}
$this->sleep(1);
}
diff --git a/src/error/PhutilErrorHandler.php b/src/error/PhutilErrorHandler.php
--- a/src/error/PhutilErrorHandler.php
+++ b/src/error/PhutilErrorHandler.php
@@ -407,7 +407,7 @@
error_log($default_message);
break;
default:
- error_log('Unknown event '.$event);
+ error_log(pht('Unknown event %s', $event));
break;
}
diff --git a/src/error/PhutilOpaqueEnvelope.php b/src/error/PhutilOpaqueEnvelope.php
--- a/src/error/PhutilOpaqueEnvelope.php
+++ b/src/error/PhutilOpaqueEnvelope.php
@@ -48,7 +48,7 @@
* @task envelope
*/
public function __toString() {
- return '<opaque envelope>';
+ return pht('<opaque envelope>');
}
diff --git a/src/error/__tests__/PhutilErrorHandlerTestCase.php b/src/error/__tests__/PhutilErrorHandlerTestCase.php
--- a/src/error/__tests__/PhutilErrorHandlerTestCase.php
+++ b/src/error/__tests__/PhutilErrorHandlerTestCase.php
@@ -29,7 +29,7 @@
$old_log = ini_get('error_log');
ini_set('error_log', (string)$temporary_log);
- trigger_error('(A synthetic error emitted during a unit test.)');
+ trigger_error(pht('(A synthetic error emitted during a unit test.)'));
ini_set('error_log', $old_log);
return Filesystem::readFile($temporary_log);
diff --git a/src/filesystem/FileFinder.php b/src/filesystem/FileFinder.php
--- a/src/filesystem/FileFinder.php
+++ b/src/filesystem/FileFinder.php
@@ -187,9 +187,12 @@
if (!is_dir($this->root) || !is_readable($this->root)) {
throw new Exception(
- "Invalid FileFinder root directory specified ('{$this->root}'). ".
- "Root directory must be a directory, be readable, and be specified ".
- "with an absolute path.");
+ pht(
+ "Invalid %s root directory specified ('%s'). Root directory ".
+ "must be a directory, be readable, and be specified with an ".
+ "absolute path.",
+ __CLASS__,
+ $this->root));
}
if ($this->forceMode == 'shell') {
diff --git a/src/filesystem/Filesystem.php b/src/filesystem/Filesystem.php
--- a/src/filesystem/Filesystem.php
+++ b/src/filesystem/Filesystem.php
@@ -42,7 +42,7 @@
if ($data === false) {
throw new FilesystemException(
$path,
- "Failed to read file `{$path}'.");
+ pht("Failed to read file `%s'.", $path));
}
return $data;
@@ -91,7 +91,7 @@
if (@file_put_contents($path, $data) === false) {
throw new FilesystemException(
$path,
- "Failed to write file `{$path}'.");
+ pht("Failed to write file `%s'.", $path));
}
}
@@ -127,8 +127,7 @@
if (!$temp) {
throw new FilesystemException(
$dir,
- "unable to create temporary file in $dir"
- );
+ pht('Unable to create temporary file in %s.', $dir));
}
try {
self::writeFile($temp, $data);
@@ -140,8 +139,7 @@
if (!$ok) {
throw new FilesystemException(
$path,
- "unable to move $temp to $path"
- );
+ pht('Unable to move %s to %s.', $temp, $path));
}
} catch (Exception $e) {
// Make best effort to remove temp file
@@ -235,18 +233,19 @@
if (($fh = fopen($path, 'a')) === false) {
throw new FilesystemException(
- $path, "Failed to open file `{$path}'.");
+ $path,
+ pht("Failed to open file `%s'.", $path));
}
$dlen = strlen($data);
if (fwrite($fh, $data) !== $dlen) {
throw new FilesystemException(
$path,
- "Failed to write {$dlen} bytes to `{$path}'.");
+ pht("Failed to write %d bytes to `%s'.", $dlen, $path));
}
if (!fflush($fh) || !fclose($fh)) {
throw new FilesystemException(
$path,
- "Failed closing file `{$path}' after write.");
+ pht("Failed closing file `%s' after write.", $path));
}
}
@@ -262,7 +261,10 @@
public static function remove($path) {
if (!strlen($path)) {
// Avoid removing PWD.
- throw new Exception('No path provided to remove().');
+ throw new Exception(
+ pht(
+ 'No path provided to %s.',
+ __FUNCTION__.'()'));
}
$path = self::resolvePath($path);
@@ -292,7 +294,7 @@
if (!$ok) {
throw new FilesystemException(
$new,
- "Failed to rename '{$old}' to '{$new}'!");
+ pht("Failed to rename '%s' to '%s'!", $old, $new));
}
}
@@ -315,14 +317,14 @@
if (!$ok) {
throw new FilesystemException(
$path,
- "Failed to remove directory '{$path}'!");
+ pht("Failed to remove directory '%s'!", $path));
}
} else {
$ok = unlink($path);
if (!$ok) {
throw new FilesystemException(
$path,
- "Failed to remove file '{$path}'!");
+ pht("Failed to remove file '%s'!", $path));
}
}
}
@@ -346,7 +348,8 @@
if (!@chmod($path, $umask)) {
$readable_umask = sprintf('%04o', $umask);
throw new FilesystemException(
- $path, "Failed to chmod `{$path}' to `{$readable_umask}'.");
+ $path,
+ pht("Failed to chmod `%s' to `%s'.", $path, $readable_umask));
}
}
@@ -370,7 +373,7 @@
if ($modified_time === false) {
throw new FilesystemException(
$path,
- 'Failed to read modified time for '.$path);
+ pht('Failed to read modified time for %s.', $path));
}
return $modified_time;
@@ -406,14 +409,16 @@
if ($data === false) {
throw new Exception(
- pht('openssl_random_pseudo_bytes() failed to generate entropy!'));
+ pht(
+ '%s failed to generate entropy!',
+ 'openssl_random_pseudo_bytes()'));
}
if (strlen($data) != $number_of_bytes) {
throw new Exception(
pht(
- 'openssl_random_pseudo_bytes() returned an unexpected number of '.
- 'bytes (got %d, expected %d)!',
+ '%s returned an unexpected number of bytes (got %d, expected %d)!',
+ 'openssl_random_pseudo_bytes()',
strlen($data),
$number_of_bytes));
}
@@ -433,7 +438,7 @@
if (strlen($data) != $number_of_bytes) {
throw new FilesystemException(
'/dev/urandom',
- 'Failed to read random bytes!');
+ pht('Failed to read random bytes!'));
}
return $data;
}
@@ -448,17 +453,20 @@
if (phutil_is_windows()) {
throw new Exception(
pht(
- 'Filesystem::readRandomBytes() requires the PHP OpenSSL extension '.
- 'to be installed and enabled to access an entropy source. On '.
- 'Windows, this extension is usually installed but not enabled by '.
- 'default. Enable it in your "php.ini".'));
+ '%s requires the PHP OpenSSL extension to be installed and enabled '.
+ 'to access an entropy source. On Windows, this extension is usually '.
+ 'installed but not enabled by default. Enable it in your "s".',
+ __METHOD__.'()',
+ 'php.ini'));
}
throw new Exception(
pht(
- 'Filesystem::readRandomBytes() requires the PHP OpenSSL extension '.
- 'or access to "/dev/urandom". Install or enable the OpenSSL '.
- 'extension, or make sure "/dev/urandom" is accessible.'));
+ '%s requires the PHP OpenSSL extension or access to "%s". Install or '.
+ 'enable the OpenSSL extension, or make sure "%s" is accessible.',
+ __METHOD__.'()',
+ '/dev/urandom',
+ '/dev/urandom'));
}
@@ -619,7 +627,7 @@
if (!mkdir($path, $umask)) {
throw new FilesystemException(
$path,
- "Failed to create directory `{$path}'.");
+ pht("Failed to create directory `%s'.", $path));
}
// Need to change permissions explicitly because mkdir does something
@@ -653,7 +661,8 @@
$tmp = sys_get_temp_dir();
if (!$tmp) {
throw new FilesystemException(
- $tmp, 'Unable to determine system temporary directory.');
+ $tmp,
+ pht('Unable to determine system temporary directory.'));
}
$base = $tmp.DIRECTORY_SEPARATOR.$prefix;
@@ -665,7 +674,7 @@
self::createDirectory($dir, $umask);
break;
} catch (FilesystemException $ex) {
- // Ignore.
+ // Ignore.
}
} while (--$tries);
@@ -708,7 +717,7 @@
if ($list === false) {
throw new FilesystemException(
$path,
- "Unable to list contents of directory `{$path}'.");
+ pht("Unable to list contents of directory `%s'.", $path));
}
foreach ($list as $k => $v) {
@@ -974,7 +983,7 @@
if (!self::pathExists($path)) {
throw new FilesystemException(
$path,
- "Filesystem entity `{$path}' does not exist.");
+ pht("Filesystem entity `%s' does not exist.", $path));
}
}
@@ -991,7 +1000,7 @@
if (file_exists($path) || is_link($path)) {
throw new FilesystemException(
$path,
- "Path `{$path}' already exists!");
+ pht("Path `%s' already exists!", $path));
}
}
@@ -1008,7 +1017,7 @@
if (!is_file($path)) {
throw new FilesystemException(
$path,
- "Requested path `{$path}' is not a file.");
+ pht("Requested path `%s' is not a file.", $path));
}
}
@@ -1025,7 +1034,7 @@
if (!is_dir($path)) {
throw new FilesystemException(
$path,
- "Requested path `{$path}' is not a directory.");
+ pht("Requested path `%s' is not a directory.", $path));
}
}
@@ -1042,7 +1051,7 @@
if (!is_writable($path)) {
throw new FilesystemException(
$path,
- "Requested path `{$path}' is not writable.");
+ pht("Requested path `%s' is not writable.", $path));
}
}
@@ -1059,7 +1068,7 @@
if (!is_readable($path)) {
throw new FilesystemException(
$path,
- "Path `{$path}' is not readable.");
+ pht("Path `%s' is not readable.", $path));
}
}
diff --git a/src/filesystem/PhutilDeferredLog.php b/src/filesystem/PhutilDeferredLog.php
--- a/src/filesystem/PhutilDeferredLog.php
+++ b/src/filesystem/PhutilDeferredLog.php
@@ -122,7 +122,7 @@
public function setFile($file) {
if ($this->didWrite) {
throw new Exception(
- 'You can not change the logfile after a write has occurred!');
+ pht('You can not change the logfile after a write has occurred!'));
}
$this->file = $file;
return $this;
@@ -189,7 +189,7 @@
FILE_APPEND | LOCK_EX);
if ($ok === false) {
- $message = "Unable to write to logfile '{$this->file}'!";
+ $message = pht("Unable to write to logfile '%s'!", $this->file);
if ($this->failQuietly) {
phlog($message);
} else {
diff --git a/src/filesystem/PhutilDirectoryFixture.php b/src/filesystem/PhutilDirectoryFixture.php
--- a/src/filesystem/PhutilDirectoryFixture.php
+++ b/src/filesystem/PhutilDirectoryFixture.php
@@ -41,7 +41,7 @@
$ok = rename($tmp, Filesystem::resolvePath($path));
if (!$ok) {
- throw new FilesystemException($path, 'Failed to overwrite file.');
+ throw new FilesystemException($path, pht('Failed to overwrite file.'));
}
return $this;
diff --git a/src/filesystem/PhutilFileLock.php b/src/filesystem/PhutilFileLock.php
--- a/src/filesystem/PhutilFileLock.php
+++ b/src/filesystem/PhutilFileLock.php
@@ -71,7 +71,7 @@
if (!$handle) {
throw new FilesystemException(
$path,
- "Unable to open lock '{$path}' for writing!");
+ pht("Unable to open lock '%s' for writing!", $path));
}
$start_time = microtime(true);
@@ -105,12 +105,12 @@
protected function doUnlock() {
$ok = flock($this->handle, LOCK_UN | LOCK_NB);
if (!$ok) {
- throw new Exception('Unable to unlock file!');
+ throw new Exception(pht('Unable to unlock file!'));
}
$ok = fclose($this->handle);
if (!$ok) {
- throw new Exception('Unable to close file!');
+ throw new Exception(pht('Unable to close file!'));
}
$this->handle = null;
diff --git a/src/filesystem/PhutilFileTree.php b/src/filesystem/PhutilFileTree.php
--- a/src/filesystem/PhutilFileTree.php
+++ b/src/filesystem/PhutilFileTree.php
@@ -67,7 +67,7 @@
if ($this->data) {
$full_path = $this->getFullPath();
throw new Exception(
- "Duplicate insertion for path '{$full_path}'.");
+ pht("Duplicate insertion for path '%s'.", $full_path));
}
$this->data = $data;
return;
diff --git a/src/filesystem/PhutilLock.php b/src/filesystem/PhutilLock.php
--- a/src/filesystem/PhutilLock.php
+++ b/src/filesystem/PhutilLock.php
@@ -110,7 +110,8 @@
$name = $lock->getName();
if (self::getLock($name)) {
- throw new Exception("Lock '{$name}' is already registered!");
+ throw new Exception(
+ pht("Lock '%s' is already registered!", $name));
}
self::$locks[$name] = $lock;
@@ -153,7 +154,7 @@
if ($this->locked) {
$name = $this->getName();
throw new Exception(
- "Lock '{$name}' has already been locked by this process.");
+ pht("Lock '%s' has already been locked by this process.", $name));
}
$profiler = PhutilServiceProfiler::getInstance();
@@ -193,7 +194,7 @@
if (!$this->locked) {
$name = $this->getName();
throw new Exception(
- "Lock '{$name} is not locked by this process!");
+ pht("Lock '%s is not locked by this process!", $name));
}
$this->doUnlock();
diff --git a/src/filesystem/__tests__/FileFinderTestCase.php b/src/filesystem/__tests__/FileFinderTestCase.php
--- a/src/filesystem/__tests__/FileFinderTestCase.php
+++ b/src/filesystem/__tests__/FileFinderTestCase.php
@@ -23,9 +23,9 @@
$this->assertTrue(array_key_exists('test.txt', $files));
$this->assertTrue(array_key_exists('file.txt', $files));
$this->assertTrue(
- array_key_exists(
- 'include_dir.txt/subdir.txt/alsoinclude.txt',
- $files));
+ array_key_exists(
+ 'include_dir.txt/subdir.txt/alsoinclude.txt',
+ $files));
$this->assertFalse(array_key_exists('test', $files));
$this->assertTrue(array_key_exists('.hidden.txt', $files));
$this->assertFalse(array_key_exists('exclude/file.txt', $files));
@@ -89,9 +89,9 @@
$this->assertTrue(array_key_exists('test.txt', $files));
$this->assertTrue(array_key_exists('file.txt', $files));
$this->assertTrue(
- array_key_exists(
- 'include_dir.txt/subdir.txt/alsoinclude.txt',
- $files));
+ array_key_exists(
+ 'include_dir.txt/subdir.txt/alsoinclude.txt',
+ $files));
$this->assertFalse(array_key_exists('test', $files));
$this->assertTrue(array_key_exists('.hidden.txt', $files));
$this->assertFalse(array_key_exists('exclude/file.txt', $files));
@@ -116,9 +116,9 @@
// Test whether the correct files were found.
$this->assertTrue(
- array_key_exists(
- 'include_dir.txt/subdir.txt/alsoinclude.txt',
- $files));
+ array_key_exists(
+ 'include_dir.txt/subdir.txt/alsoinclude.txt',
+ $files));
// Ensure that only the one file was found.
$this->assertEqual(1, count($files));
}
diff --git a/src/filesystem/__tests__/PhutilDeferredLogTestCase.php b/src/filesystem/__tests__/PhutilDeferredLogTestCase.php
--- a/src/filesystem/__tests__/PhutilDeferredLogTestCase.php
+++ b/src/filesystem/__tests__/PhutilDeferredLogTestCase.php
@@ -123,7 +123,7 @@
$log->setFile(null);
unset($log);
- $this->assertEqual('', Filesystem::readFile($tmp), 'No Write');
+ $this->assertEqual('', Filesystem::readFile($tmp), pht('No Write'));
}
public function testDoubleWrite() {
@@ -134,7 +134,9 @@
$log->write();
unset($log);
- $this->assertEqual("xyz\n", Filesystem::readFile($tmp), 'Double Write');
+ $this->assertEqual(
+ "xyz\n",
+ Filesystem::readFile($tmp), pht('Double Write'));
}
public function testSetAfterWrite() {
@@ -151,7 +153,7 @@
$caught = $ex;
}
- $this->assertTrue($caught instanceof Exception, 'Set After Write');
+ $this->assertTrue($caught instanceof Exception, pht('Set After Write'));
}
private function checkLog($expect, $format, $data) {
diff --git a/src/filesystem/__tests__/PhutilFileLockTestCase.php b/src/filesystem/__tests__/PhutilFileLockTestCase.php
--- a/src/filesystem/__tests__/PhutilFileLockTestCase.php
+++ b/src/filesystem/__tests__/PhutilFileLockTestCase.php
@@ -167,7 +167,7 @@
}
}
- throw new Exception('Unable to hold lock in external process!');
+ throw new Exception(pht('Unable to hold lock in external process!'));
}
private function buildLockFuture($flags, $file) {
diff --git a/src/filesystem/linesofalarge/LinesOfALarge.php b/src/filesystem/linesofalarge/LinesOfALarge.php
--- a/src/filesystem/linesofalarge/LinesOfALarge.php
+++ b/src/filesystem/linesofalarge/LinesOfALarge.php
@@ -58,7 +58,8 @@
*/
final public function setDelimiter($character) {
if (strlen($character) !== 1) {
- throw new Exception('Delimiter character MUST be one byte in length.');
+ throw new Exception(
+ pht('Delimiter character MUST be one byte in length.'));
}
$this->delimiter = $character;
return $this;
diff --git a/src/filesystem/linesofalarge/LinesOfALargeExecFuture.php b/src/filesystem/linesofalarge/LinesOfALargeExecFuture.php
--- a/src/filesystem/linesofalarge/LinesOfALargeExecFuture.php
+++ b/src/filesystem/linesofalarge/LinesOfALargeExecFuture.php
@@ -69,9 +69,11 @@
protected function willRewind() {
if ($this->didRewind) {
throw new Exception(
- "You can not reiterate over a LinesOfALargeExecFuture object. The ".
- "entire goal of the construct is to avoid keeping output in memory. ".
- "What you are attempting to do is silly and doesn't make any sense.");
+ pht(
+ "You can not reiterate over a %s object. The entire goal of the ".
+ "construct is to avoid keeping output in memory. What you are ".
+ "attempting to do is silly and doesn't make any sense.",
+ __CLASS__));
}
$this->didRewind = true;
}
diff --git a/src/filesystem/linesofalarge/LinesOfALargeFile.php b/src/filesystem/linesofalarge/LinesOfALargeFile.php
--- a/src/filesystem/linesofalarge/LinesOfALargeFile.php
+++ b/src/filesystem/linesofalarge/LinesOfALargeFile.php
@@ -79,7 +79,7 @@
if (!$this->handle) {
throw new FilesystemException(
$this->fileName,
- 'Failed to open file!');
+ pht('Failed to open file!'));
}
}
@@ -98,7 +98,7 @@
if ($more === false) {
throw new FilesystemException(
$this->fileName,
- 'Failed to read file!');
+ pht('Failed to read file!'));
}
return $more;
}
diff --git a/src/filesystem/linesofalarge/__tests__/LinesOfALargeExecFutureTestCase.php b/src/filesystem/linesofalarge/__tests__/LinesOfALargeExecFutureTestCase.php
--- a/src/filesystem/linesofalarge/__tests__/LinesOfALargeExecFutureTestCase.php
+++ b/src/filesystem/linesofalarge/__tests__/LinesOfALargeExecFutureTestCase.php
@@ -54,9 +54,9 @@
$this->assertEqual(
$read,
$lines,
- 'Write: '.id(new PhutilUTF8StringTruncator())
- ->setMaximumGlyphs(32)
- ->truncateString($write));
+ pht('Write: %s', id(new PhutilUTF8StringTruncator())
+ ->setMaximumGlyphs(32)
+ ->truncateString($write)));
}
}
diff --git a/src/filesystem/linesofalarge/__tests__/LinesOfALargeFileTestCase.php b/src/filesystem/linesofalarge/__tests__/LinesOfALargeFileTestCase.php
--- a/src/filesystem/linesofalarge/__tests__/LinesOfALargeFileTestCase.php
+++ b/src/filesystem/linesofalarge/__tests__/LinesOfALargeFileTestCase.php
@@ -98,9 +98,9 @@
$this->assertEqual(
$read,
$lines,
- 'Write: '.id(new PhutilUTF8StringTruncator())
- ->setMaximumGlyphs(32)
- ->truncateString($write));
+ pht('Write: %s', id(new PhutilUTF8StringTruncator())
+ ->setMaximumGlyphs(32)
+ ->truncateString($write)));
}
public function allowCatsOnly($line) {
@@ -124,9 +124,9 @@
$this->assertEqual(
$read,
$lines,
- 'Write: '.id(new PhutilUTF8StringTruncator())
- ->setMaximumGlyphs(32)
- ->truncateString($write));
+ pht('Write: %s', id(new PhutilUTF8StringTruncator())
+ ->setMaximumGlyphs(32)
+ ->truncateString($write)));
}
}
diff --git a/src/future/Future.php b/src/future/Future.php
--- a/src/future/Future.php
+++ b/src/future/Future.php
@@ -128,7 +128,7 @@
// long as we have a handler registered.
if (function_exists('pcntl_signal')) {
if (!pcntl_signal(SIGCHLD, array('Future', 'handleSIGCHLD'))) {
- throw new Exception('Failed to install signal handler!');
+ throw new Exception(pht('Failed to install signal handler!'));
}
}
self::$handlerInstalled = true;
diff --git a/src/future/FutureIterator.php b/src/future/FutureIterator.php
--- a/src/future/FutureIterator.php
+++ b/src/future/FutureIterator.php
@@ -84,7 +84,7 @@
$this->futures[$key] = $future;
$this->wait[] = $key;
} else {
- throw new Exception("Invalid key {$key}");
+ throw new Exception(pht('Invalid key %s', $key));
}
// Start running the future if we don't have $this->limit futures running
diff --git a/src/future/FutureProxy.php b/src/future/FutureProxy.php
--- a/src/future/FutureProxy.php
+++ b/src/future/FutureProxy.php
@@ -23,7 +23,7 @@
protected function getProxiedFuture() {
if (!$this->proxied) {
- throw new Exception('The proxied future has not been provided yet.');
+ throw new Exception(pht('The proxied future has not been provided yet.'));
}
return $this->proxied;
}
diff --git a/src/future/asana/PhutilAsanaFuture.php b/src/future/asana/PhutilAsanaFuture.php
--- a/src/future/asana/PhutilAsanaFuture.php
+++ b/src/future/asana/PhutilAsanaFuture.php
@@ -33,11 +33,17 @@
$params = $this->params;
if (!$this->action) {
- throw new Exception('You must setRawAsanaQuery()!');
+ throw new Exception(
+ pht(
+ 'You must %s!',
+ 'setRawAsanaQuery()'));
}
if (!$this->accessToken) {
- throw new Exception('You must setAccessToken()!');
+ throw new Exception(
+ pht(
+ 'You must %s!',
+ 'setAccessToken()'));
}
$uri = new PhutilURI('https://app.asana.com/');
@@ -72,7 +78,10 @@
if (idx($data, 'errors')) {
$errors = print_r($data['errors'], true);
- throw new Exception("Received errors from Asana: {$errors}");
+ throw new Exception(
+ pht(
+ 'Received errors from Asana: %s',
+ $errors));
}
return $data['data'];
diff --git a/src/future/aws/PhutilAWSException.php b/src/future/aws/PhutilAWSException.php
--- a/src/future/aws/PhutilAWSException.php
+++ b/src/future/aws/PhutilAWSException.php
@@ -12,8 +12,8 @@
$this->params = $params;
$desc = array();
- $desc[] = 'AWS Request Failed';
- $desc[] = 'HTTP Status Code: '.$http_status;
+ $desc[] = pht('AWS Request Failed');
+ $desc[] = pht('HTTP Status Code: %d', $http_status);
if ($this->requestID) {
$desc[] = 'AWS Request ID: '.$this->requestID;
@@ -26,7 +26,7 @@
}
}
} else {
- $desc[] = 'Response Body: '.idx($params, 'body');
+ $desc[] = pht('Response Body: %s', idx($params, 'body'));
}
$desc = implode("\n", $desc);
diff --git a/src/future/aws/PhutilAWSFuture.php b/src/future/aws/PhutilAWSFuture.php
--- a/src/future/aws/PhutilAWSFuture.php
+++ b/src/future/aws/PhutilAWSFuture.php
@@ -54,11 +54,17 @@
$params = $this->params;
if (!$this->params) {
- throw new Exception('You must setRawAWSQuery()!');
+ throw new Exception(
+ pht(
+ 'You must %s!',
+ 'setRawAWSQuery()'));
}
if (!$this->getAWSAccessKey()) {
- throw new Exception('You must setAWSKeys()!');
+ throw new Exception(
+ pht(
+ 'You must %s!',
+ 'setAWSKeys()'));
}
$params['AWSAccessKeyId'] = $this->getAWSAccessKey();
diff --git a/src/future/exec/CommandException.php b/src/future/exec/CommandException.php
--- a/src/future/exec/CommandException.php
+++ b/src/future/exec/CommandException.php
@@ -61,7 +61,7 @@
$len = strlen($string);
if ($len > $limit) {
$cut = $len - $limit;
- $suffix = '... ('.number_format($cut).' more bytes) ...';
+ $suffix = pht('... (%d more bytes) ...', number_format($cut));
if ($cut > strlen($suffix)) {
$string = substr($string, 0, $limit).$suffix;
}
diff --git a/src/future/exec/ExecFuture.php b/src/future/exec/ExecFuture.php
--- a/src/future/exec/ExecFuture.php
+++ b/src/future/exec/ExecFuture.php
@@ -414,7 +414,7 @@
if ($err) {
$cmd = $this->command;
throw new CommandException(
- "Command failed with error #{$err}!",
+ pht('Command failed with error #%d!', $err),
$cmd,
$err,
$stdout,
@@ -439,8 +439,10 @@
if (strlen($stderr)) {
$cmd = $this->command;
throw new CommandException(
- "JSON command '{$cmd}' emitted text to stderr when none was expected: ".
- $stderr,
+ pht(
+ "JSON command '%s' emitted text to stderr when none was expected: %d",
+ $cmd,
+ $stderr),
$cmd,
0,
$stdout,
@@ -587,7 +589,7 @@
do {
$data = fread($stream, min($length, 64 * 1024));
if (false === $data) {
- throw new Exception('Failed to read from '.$description);
+ throw new Exception(pht('Failed to read from %s', $description));
}
$read_bytes = strlen($data);
@@ -733,7 +735,11 @@
}
if (!is_resource($proc)) {
- throw new Exception("Failed to proc_open(): {$err}");
+ throw new Exception(
+ pht(
+ 'Failed to %s: %s',
+ 'proc_open()',
+ $err));
}
$this->pipes = $pipes;
@@ -751,7 +757,7 @@
(!stream_set_blocking($stderr, false)) ||
(!stream_set_blocking($stdin, false))) {
$this->__destruct();
- throw new Exception('Failed to set streams nonblocking.');
+ throw new Exception(pht('Failed to set streams nonblocking.'));
}
}
@@ -771,7 +777,7 @@
$bytes = fwrite($stdin, $write_segment);
if ($bytes === false) {
- throw new Exception('Unable to write to stdin!');
+ throw new Exception(pht('Unable to write to stdin!'));
} else if ($bytes) {
$this->stdin->removeBytesFromHead($bytes);
} else {
diff --git a/src/future/exec/PhutilExecPassthru.php b/src/future/exec/PhutilExecPassthru.php
--- a/src/future/exec/PhutilExecPassthru.php
+++ b/src/future/exec/PhutilExecPassthru.php
@@ -96,7 +96,11 @@
$trap->destroy();
if (!is_resource($proc)) {
- throw new Exception("Failed to passthru proc_open(): {$errors}");
+ throw new Exception(
+ pht(
+ 'Failed to passthru %s: %s',
+ 'proc_open()',
+ $errors));
}
$err = proc_close($proc);
diff --git a/src/future/http/BaseHTTPFuture.php b/src/future/http/BaseHTTPFuture.php
--- a/src/future/http/BaseHTTPFuture.php
+++ b/src/future/http/BaseHTTPFuture.php
@@ -96,10 +96,12 @@
);
if (empty($supported_methods[$method])) {
- $method_list = implode(', ', array_keys($supported_methods));
throw new Exception(
- "The HTTP method '{$method}' is not supported. Supported HTTP methods ".
- "are: {$method_list}.");
+ pht(
+ "The HTTP method '%s' is not supported. Supported HTTP methods ".
+ "are: %s.",
+ $method,
+ implode(', ', array_keys($supported_methods))));
}
$this->method = $method;
@@ -155,7 +157,7 @@
*/
public function setData($data) {
if (!is_string($data) && !is_array($data)) {
- throw new Exception('Data parameter must be an array or string.');
+ throw new Exception(pht('Data parameter must be an array or string.'));
}
$this->data = $data;
return $this;
diff --git a/src/future/http/HTTPFuture.php b/src/future/http/HTTPFuture.php
--- a/src/future/http/HTTPFuture.php
+++ b/src/future/http/HTTPFuture.php
@@ -43,17 +43,20 @@
public function setURI($uri) {
$parts = parse_url($uri);
if (!$parts) {
- throw new Exception("Could not parse URI '{$uri}'.");
+ throw new Exception(pht("Could not parse URI '%s'.", $uri));
}
if (empty($parts['scheme']) || $parts['scheme'] !== 'http') {
throw new Exception(
- "URI '{$uri}' must be fully qualified with 'http://' scheme.");
+ pht(
+ "URI '%s' must be fully qualified with '%s' scheme.",
+ $uri,
+ 'http://'));
}
if (!isset($parts['host'])) {
throw new Exception(
- "URI '{$uri}' must be fully qualified and include host name.");
+ pht("URI '%s' must be fully qualified and include host name.", $uri));
}
$this->host = $parts['host'];
@@ -64,7 +67,7 @@
if (isset($parts['user']) || isset($parts['pass'])) {
throw new Exception(
- 'HTTP Basic Auth is not supported by HTTPFuture.');
+ pht('HTTP Basic Auth is not supported by %s.', __CLASS__));
}
if (isset($parts['path'])) {
@@ -143,7 +146,7 @@
if (strlen($this->writeBuffer)) {
$bytes = @fwrite($this->socket, $this->writeBuffer);
if ($bytes === false) {
- throw new Exception('Failed to write to buffer.');
+ throw new Exception(pht('Failed to write to buffer.'));
} else if ($bytes) {
$this->writeBuffer = substr($this->writeBuffer, $bytes);
}
@@ -158,7 +161,7 @@
}
if ($data === false) {
- throw new Exception('Failed to read socket.');
+ throw new Exception(pht('Failed to read socket.'));
}
}
@@ -184,7 +187,7 @@
$ok = stream_set_blocking($socket, 0);
if (!$ok) {
- throw new Exception('Failed to set stream nonblocking.');
+ throw new Exception(pht('Failed to set stream nonblocking.'));
}
$this->writeBuffer = $this->buildHTTPRequest();
diff --git a/src/future/http/HTTPSFuture.php b/src/future/http/HTTPSFuture.php
--- a/src/future/http/HTTPSFuture.php
+++ b/src/future/http/HTTPSFuture.php
@@ -162,9 +162,10 @@
if (isset($this->files[$key])) {
throw new Exception(
pht(
- 'HTTPSFuture currently supports only one file attachment for each '.
+ '%s currently supports only one file attachment for each '.
'parameter name. You are trying to attach two different files with '.
'the same parameter, "%s".',
+ __CLASS__,
$key));
}
@@ -196,7 +197,7 @@
if (!self::$multi) {
self::$multi = curl_multi_init();
if (!self::$multi) {
- throw new Exception('curl_multi_init() failed!');
+ throw new Exception(pht('%s failed!', 'curl_multi_init()'));
}
}
@@ -205,7 +206,7 @@
} else {
$curl = curl_init();
if (!$curl) {
- throw new Exception('curl_init() failed!');
+ throw new Exception(pht('%s failed!', 'curl_init()'));
}
}
@@ -543,7 +544,8 @@
pht(
'Request specifies two values for key "%s", but parameter '.
'names must be unique if you are posting file data due to '.
- 'limitations with cURL.'));
+ 'limitations with cURL.',
+ $key));
}
$map[$key] = $value;
}
@@ -559,10 +561,10 @@
if (array_key_exists($name, $data)) {
throw new Exception(
pht(
- 'Request specifies a file with key "%s", but that key is '.
- 'also defined by normal request data. Due to limitations '.
- 'with cURL, requests that post file data must use unique '.
- 'keys.'));
+ 'Request specifies a file with key "%s", but that key is also '.
+ 'defined by normal request data. Due to limitations with cURL, '.
+ 'requests that post file data must use unique keys.',
+ $name));
}
$tmp = new TempFile($info['name']);
@@ -603,9 +605,11 @@
throw new Exception(
pht(
'Attempting to make an HTTP request, but query string data begins '.
- 'with "@". Prior to PHP 5.2.0 this reads files off disk, which '.
+ 'with "%s". Prior to PHP 5.2.0 this reads files off disk, which '.
'creates a wide attack window for security vulnerabilities. '.
- 'Upgrade PHP or avoid making cURL requests which begin with "@".'));
+ 'Upgrade PHP or avoid making cURL requests which begin with "%s".',
+ '@',
+ '@'));
}
// This is safe if we're on PHP 5.2.0 or newer.
@@ -614,11 +618,11 @@
throw new Exception(
pht(
- 'Attempting to make an HTTP request which includes file data, but '.
- 'the value of a query parameter begins with "@". PHP interprets '.
- 'these values to mean that it should read arbitrary files off disk '.
- 'and transmit them to remote servers. Declining to make this '.
- 'request.'));
+ 'Attempting to make an HTTP request which includes file data, but the '.
+ 'value of a query parameter begins with "%s". PHP interprets these '.
+ 'values to mean that it should read arbitrary files off disk and '.
+ 'transmit them to remote servers. Declining to make this request.',
+ '@'));
}
diff --git a/src/future/http/status/HTTPFutureCURLResponseStatus.php b/src/future/http/status/HTTPFutureCURLResponseStatus.php
--- a/src/future/http/status/HTTPFutureCURLResponseStatus.php
+++ b/src/future/http/status/HTTPFutureCURLResponseStatus.php
@@ -32,47 +32,51 @@
}
$map = array(
- CURLE_COULDNT_RESOLVE_HOST =>
+ CURLE_COULDNT_RESOLVE_HOST => pht(
'There was an error resolving the server hostname. Check that you are '.
'connected to the internet and that DNS is correctly configured. (Did '.
- 'you add the domain to `/etc/hosts` on some other machine, but not '.
- 'this one?)',
+ 'you add the domain to `%s` on some other machine, but not this one?)',
+ '/etc/hosts'),
- CURLE_SSL_CACERT =>
+ CURLE_SSL_CACERT => pht(
'There was an error verifying the SSL Certificate Authority while '.
'negotiating the SSL connection. This usually indicates that you are '.
'using a self-signed certificate but have not added your CA to the '.
- 'CA bundle. See instructions in "libphutil/resources/ssl/README".',
+ 'CA bundle. See instructions in "%s".',
+ 'libphutil/resources/ssl/README'),
// Apparently there's no error constant for this? In cURL it's
// CURLE_SSL_CACERT_BADFILE but there's no corresponding constant in
// PHP.
- 77 =>
+ 77 => pht(
'The SSL CA Bundles that we tried to use could not be read or are '.
- 'not formatted correctly.',
+ 'not formatted correctly.'),
- CURLE_SSL_CONNECT_ERROR =>
+ CURLE_SSL_CONNECT_ERROR => pht(
'There was an error negotiating the SSL connection. This usually '.
'indicates that the remote host has a bad SSL certificate, or your '.
'local host has some sort of SSL misconfiguration which prevents it '.
'from accepting the CA. If you are using a self-signed certificate, '.
- 'see instructions in "libphutil/resources/ssl/README".',
+ 'see instructions in "%s".',
+ 'libphutil/resources/ssl/README'),
- CURLE_OPERATION_TIMEOUTED =>
- 'The request took too long to complete.',
+ CURLE_OPERATION_TIMEOUTED => pht(
+ 'The request took too long to complete.'),
- CURLE_SSL_PEER_CERTIFICATE =>
+ CURLE_SSL_PEER_CERTIFICATE => pht(
'There was an error verifying the SSL connection. This usually '.
'indicates that the remote host has an SSL certificate for a '.
'different domain name than you are connecting with. Make sure the '.
- 'certificate you have installed is signed for the correct domain.',
+ 'certificate you have installed is signed for the correct domain.'),
);
- $default_message =
+ $default_message = pht(
"The cURL library raised an error while making a request. You may be ".
- "able to find more information about this error (error code: {$code}) ".
- "on the cURL site: http://curl.haxx.se/libcurl/c/libcurl-errors.html#".
- preg_replace('/[^A-Z]/', '', $constant_name);
+ 'able to find more information about this error (error code: %d) '.
+ 'on the cURL site: %s',
+ $code,
+ 'http://curl.haxx.se/libcurl/c/libcurl-errors.html#'.
+ preg_replace('/[^A-Z]/', '', $constant_name));
$detailed_message = idx($map, $code, $default_message);
diff --git a/src/future/http/status/HTTPFutureCertificateResponseStatus.php b/src/future/http/status/HTTPFutureCertificateResponseStatus.php
--- a/src/future/http/status/HTTPFutureCertificateResponseStatus.php
+++ b/src/future/http/status/HTTPFutureCertificateResponseStatus.php
@@ -26,8 +26,8 @@
"You can do this with `security add-trusted-cert` from the command ".
"line, or by visiting the site in Safari and choosing to trust the ".
"certificate permanently.\n\n".
- 'For more information, see instructions in '.
- '"libphutil/resources/ssl/README".');
+ 'For more information, see instructions in "%s".',
+ 'libphutil/resources/ssl/README');
}
}
diff --git a/src/future/http/status/HTTPFutureParseResponseStatus.php b/src/future/http/status/HTTPFutureParseResponseStatus.php
--- a/src/future/http/status/HTTPFutureParseResponseStatus.php
+++ b/src/future/http/status/HTTPFutureParseResponseStatus.php
@@ -22,9 +22,9 @@
}
protected function getErrorCodeDescription($code) {
- return
- 'The remote host returned something other than an HTTP response: '.
- $this->rawResponse;
+ return pht(
+ 'The remote host returned something other than an HTTP response: %s',
+ $this->rawResponse);
}
}
diff --git a/src/future/http/status/HTTPFutureTransportResponseStatus.php b/src/future/http/status/HTTPFutureTransportResponseStatus.php
--- a/src/future/http/status/HTTPFutureTransportResponseStatus.php
+++ b/src/future/http/status/HTTPFutureTransportResponseStatus.php
@@ -21,21 +21,22 @@
protected function getErrorCodeDescription($code) {
$map = array(
- self::ERROR_TIMEOUT =>
- 'The request took too long to complete.',
- self::ERROR_CONNECTION_ABORTED =>
- 'The remote host closed the connection before the request completed.',
- self::ERROR_CONNECTION_REFUSED =>
+ self::ERROR_TIMEOUT => pht(
+ 'The request took too long to complete.'),
+ self::ERROR_CONNECTION_ABORTED => pht(
+ 'The remote host closed the connection before the request completed.'),
+ self::ERROR_CONNECTION_REFUSED => pht(
'The remote host refused the connection. This usually means the '.
'host is not running an HTTP server, or the network is blocking '.
'connections from this machine. Verify you can connect to the '.
- 'remote host from this host.',
- self::ERROR_CONNECTION_FAILED =>
+ 'remote host from this host.'),
+ self::ERROR_CONNECTION_FAILED => pht(
'Connection could not be initiated. This usually indicates a DNS '.
'problem: verify the domain name is correct, that you can '.
'perform a DNS lookup for it from this machine. (Did you add the '.
- 'domain to `/etc/hosts` on some other machine, but not this one?) '.
+ 'domain to `%s` on some other machine, but not this one?) '.
'This might also indicate that you specified the wrong port.',
+ '/etc/hosts'),
);
return idx($map, $code);
}
diff --git a/src/future/oauth/PhutilOAuth1Future.php b/src/future/oauth/PhutilOAuth1Future.php
--- a/src/future/oauth/PhutilOAuth1Future.php
+++ b/src/future/oauth/PhutilOAuth1Future.php
@@ -220,7 +220,10 @@
case 'HMAC-SHA1':
if (!$this->consumerSecret) {
throw new Exception(
- "Signature method 'HMAC-SHA1' requires setConsumerSecret()!");
+ pht(
+ "Signature method '%s' requires %s!",
+ 'HMAC-SHA1',
+ 'setConsumerSecret()'));
}
$hash = hash_hmac('sha1', $string, $key, true);
@@ -228,23 +231,26 @@
case 'RSA-SHA1':
if (!$this->privateKey) {
throw new Exception(
- "Signature method 'RSA-SHA1' requires setPrivateKey()!");
+ pht(
+ "Signature method '%s' requires %s!",
+ 'RSA-SHA1',
+ 'setPrivateKey()'));
}
$cert = @openssl_pkey_get_private($this->privateKey->openEnvelope());
if (!$cert) {
- throw new Exception('openssl_pkey_get_private() failed!');
+ throw new Exception(pht('%S failed!', 'openssl_pkey_get_private()'));
}
$pkey = @openssl_get_privatekey($cert);
if (!$pkey) {
- throw new Exception('openssl_get_privatekey() failed!');
+ throw new Exception(pht('%s failed!', 'openssl_get_privatekey()'));
}
$signature = null;
$ok = openssl_sign($string, $signature, $pkey, OPENSSL_ALGO_SHA1);
if (!$ok) {
- throw new Exception('openssl_sign() failed!');
+ throw new Exception(pht('%s failed!', 'openssl_sign()'));
}
openssl_free_key($pkey);
@@ -253,11 +259,14 @@
case 'PLAINTEXT':
if (!$this->consumerSecret) {
throw new Exception(
- "Signature method 'PLAINTEXT' requires setConsumerSecret()!");
+ pht(
+ "Signature method '%s' requires %s!",
+ 'PLAINTEXT',
+ 'setConsumerSecret()'));
}
return $key;
default:
- throw new Exception("Unknown signature method '{$string}'!");
+ throw new Exception(pht("Unknown signature method '%s'!", $string));
}
}
diff --git a/src/future/paypal/PhutilPayPalAPIFuture.php b/src/future/paypal/PhutilPayPalAPIFuture.php
--- a/src/future/paypal/PhutilPayPalAPIFuture.php
+++ b/src/future/paypal/PhutilPayPalAPIFuture.php
@@ -48,11 +48,11 @@
$params = $this->params;
if (!$this->params) {
- throw new Exception('You must setRawPayPalQuery()!');
+ throw new Exception(pht('You must %s!', 'setRawPayPalQuery()'));
}
if (!$this->apiUsername) {
- throw new Exception('You must set PayPal API credentials!');
+ throw new Exception(pht('You must set PayPal API credentials!'));
}
$params['VERSION'] = '98.0';
@@ -79,7 +79,7 @@
if (idx($dict, 'ACK') !== 'Success') {
throw new Exception(
- 'PayPal API call failed: '.print_r($dict, true));
+ pht('PayPal API call failed: %s', print_r($dict, true)));
}
return $dict;
diff --git a/src/future/twitch/PhutilTwitchFuture.php b/src/future/twitch/PhutilTwitchFuture.php
--- a/src/future/twitch/PhutilTwitchFuture.php
+++ b/src/future/twitch/PhutilTwitchFuture.php
@@ -39,11 +39,11 @@
$params = $this->params;
if (!$this->action) {
- throw new Exception('You must setRawTwitchQuery()!');
+ throw new Exception(pht('You must %s!', 'setRawTwitchQuery()'));
}
if (!$this->accessToken) {
- throw new Exception('You must setAccessToken()!');
+ throw new Exception(pht('You must %s!', 'setAccessToken()'));
}
$uri = new PhutilURI('https://api.twitch.tv/');
@@ -84,7 +84,7 @@
if (idx($data, 'error')) {
$error = $data['error'];
- throw new Exception("Received error from Twitch: {$error}");
+ throw new Exception(pht('Received error from Twitch: %s', $error));
}
return $data;
diff --git a/src/future/wordpress/PhutilWordPressFuture.php b/src/future/wordpress/PhutilWordPressFuture.php
--- a/src/future/wordpress/PhutilWordPressFuture.php
+++ b/src/future/wordpress/PhutilWordPressFuture.php
@@ -39,11 +39,11 @@
$params = $this->params;
if (!$this->action) {
- throw new Exception('You must setRawWordPressQuery()!');
+ throw new Exception(pht('You must %s!', 'setRawWordPressQuery()'));
}
if (!$this->accessToken) {
- throw new Exception('You must setAccessToken()!');
+ throw new Exception(pht('You must %s!', 'setAccessToken()'));
}
$uri = new PhutilURI('https://public-api.wordpress.com/');
diff --git a/src/grammar/PhutilContextFreeGrammar.php b/src/grammar/PhutilContextFreeGrammar.php
--- a/src/grammar/PhutilContextFreeGrammar.php
+++ b/src/grammar/PhutilContextFreeGrammar.php
@@ -25,7 +25,7 @@
final protected function applyRules($input, &$count, array $rules) {
if (++$count > $this->limit) {
- throw new Exception('Token replacement count exceeded limit!');
+ throw new Exception(pht('Token replacement count exceeded limit!'));
}
$matches = null;
@@ -43,7 +43,7 @@
}
if (empty($rules[$token_name])) {
- throw new Exception("Invalid token '{$token_name}' in grammar.");
+ throw new Exception(pht("Invalid token '%s' in grammar.", $token_name));
}
$key = array_rand($rules[$token_name]);
diff --git a/src/internationalization/PhutilLocale.php b/src/internationalization/PhutilLocale.php
--- a/src/internationalization/PhutilLocale.php
+++ b/src/internationalization/PhutilLocale.php
@@ -119,9 +119,10 @@
} else {
throw new Exception(
pht(
- 'Two subclasses of "PhutilLocale" ("%s" and "%s") define '.
+ 'Two subclasses of "%s" ("%s" and "%s") define '.
'locales with the same locale code ("%s"). Each locale must '.
'have a unique locale code.',
+ __CLASS__,
get_class($object),
get_class($locale_map[$locale_code]),
$locale_code));
diff --git a/src/internationalization/PhutilTranslator.php b/src/internationalization/PhutilTranslator.php
--- a/src/internationalization/PhutilTranslator.php
+++ b/src/internationalization/PhutilTranslator.php
@@ -98,7 +98,7 @@
// too many parameters), show the bad template with a note instead of
// returning an empty string. This makes it easier to figure out what
// went wrong and fix it.
- $result = '[Invalid Translation!] '.$translation;
+ $result = pht('[Invalid Translation!] %s', $translation);
}
if ($this->shouldPostProcess) {
@@ -161,7 +161,7 @@
return $plural;
default:
- throw new Exception("Unknown language '{$this->language}'.");
+ throw new Exception(pht("Unknown language '%s'.", $this->language));
}
}
diff --git a/src/internationalization/__tests__/PhutilPersonTest.php b/src/internationalization/__tests__/PhutilPersonTest.php
--- a/src/internationalization/__tests__/PhutilPersonTest.php
+++ b/src/internationalization/__tests__/PhutilPersonTest.php
@@ -14,7 +14,7 @@
}
public function __toString() {
- return 'Test ('.$this->sex.')';
+ return pht('Test (%s)', $this->sex);
}
}
diff --git a/src/internationalization/__tests__/PhutilTranslatorTestCase.php b/src/internationalization/__tests__/PhutilTranslatorTestCase.php
--- a/src/internationalization/__tests__/PhutilTranslatorTestCase.php
+++ b/src/internationalization/__tests__/PhutilTranslatorTestCase.php
@@ -204,7 +204,11 @@
$this->assertEqual(
$expect,
$translator->validateTranslation($original, $translation),
- "'{$original}' should be {$valid} with '{$translation}'.");
+ pht(
+ "'%s' should be %s with '%s'.",
+ $original,
+ $valid,
+ $translation));
}
}
}
diff --git a/src/ip/PhutilCIDRBlock.php b/src/ip/PhutilCIDRBlock.php
--- a/src/ip/PhutilCIDRBlock.php
+++ b/src/ip/PhutilCIDRBlock.php
@@ -27,8 +27,9 @@
throw new Exception(
pht(
'CIDR block "%s" is not formatted correctly. Expected an IP block '.
- 'in CIDR notation, like "172.30.0.0/16".',
- $str));
+ 'in CIDR notation, like "%s".',
+ $str,
+ '172.30.0.0/16'));
}
list($ip, $mask) = explode('/', $str);
diff --git a/src/ip/PhutilIPAddress.php b/src/ip/PhutilIPAddress.php
--- a/src/ip/PhutilIPAddress.php
+++ b/src/ip/PhutilIPAddress.php
@@ -29,8 +29,9 @@
throw new Exception(
pht(
'IP address "%s" is not properly formatted. Expected an IP '.
- 'address like "23.45.67.89".',
- $str));
+ 'address like "%s".',
+ $str,
+ '23.45.67.89'));
}
$parts = array_slice($matches, 1);
diff --git a/src/lexer/PhutilLexer.php b/src/lexer/PhutilLexer.php
--- a/src/lexer/PhutilLexer.php
+++ b/src/lexer/PhutilLexer.php
@@ -109,12 +109,18 @@
if (!is_array($raw_rules)) {
$type = gettype($raw_rules);
throw new UnexpectedValueException(
- "Expected {$class}->getRawRules() to return array, got {$type}.");
+ pht(
+ 'Expected %s to return array, got %s.',
+ $class.'->getRawRules()',
+ $type));
}
if (empty($raw_rules['start'])) {
throw new UnexpectedValueException(
- "Expected {$class} rules to define rules for state 'start'.");
+ pht(
+ "Expected %s rules to define rules for state '%s'.",
+ $class,
+ 'start'));
}
$processed_rules = array();
@@ -123,16 +129,24 @@
if (!is_array($rules)) {
$type = gettype($rules);
throw new UnexpectedValueException(
- "Expected list of rules for state '{$state}' in {$class}, got ".
- "{$type}.");
+ pht(
+ "Expected list of rules for state '%s' in %s, got %s.",
+ $state,
+ $class,
+ $type));
}
foreach ($rules as $key => $rule) {
$n = count($rule);
if ($n < 2 || $n > 4) {
throw new UnexpectedValueException(
- "Expected rule '{$key}' in state '{$state}' in {$class} to have ".
- "2-4 elements (regex, token, [next state], [options]), got {$n}.");
+ pht(
+ "Expected rule '%s' in state '%s' in %s to have 2-4 elements ".
+ "(regex, token, [next state], [options]), got %d.",
+ $key,
+ $state,
+ $class,
+ $n));
}
$rule = array_values($rule);
if (count($rule) == 2) {
@@ -150,15 +164,26 @@
$value !== 'discard' &&
$value !== null) {
throw new UnexpectedValueException(
- "Rule '{$key}' in state '{$state}' in {$class} has unknown ".
- "context rule '{$value}', expected 'push', 'pop' or ".
- "'discard'.");
+ pht(
+ "Rule '%s' in state '%s' in %s has unknown ".
+ "context rule '%s', expected '%s', '%s' or '%s'.",
+ $key,
+ $state,
+ $class,
+ $value,
+ 'push',
+ 'pop',
+ 'discard'));
}
break;
default:
throw new UnexpectedValueException(
- "Rule '{$key}' in state '{$state}' in {$class} has unknown ".
- "option '{$option}'.");
+ pht(
+ "Rule '%s' in state '%s' in %s has unknown option '%s'.",
+ $key,
+ $state,
+ $class,
+ $option));
}
}
@@ -170,17 +195,27 @@
if (@preg_match($rule[0], '') === false) {
$error = error_get_last();
throw new UnexpectedValueException(
- "Rule '{$key}' in state '{$state}' in {$class} defines an ".
- "invalid regular expression ('{$rule[0]}'): ".
- idx($error, 'message'));
+ pht(
+ "Rule '%s' in state '%s' in %s defines an ".
+ "invalid regular expression ('%s'): %s",
+ $key,
+ $state,
+ $class,
+ $rule[0],
+ idx($error, 'message')));
}
$next_state = $rule[2];
if ($next_state !== null && $next_state !== '!pop') {
if (empty($raw_rules[$next_state])) {
throw new UnexpectedValueException(
- "Rule '{$key}' in state '{$state}' in {$class} transitions to ".
- "state '{$next_state}', but there are no rules for that state.");
+ pht(
+ "Rule '%s' in state '%s' in %s transitions to ".
+ "state '%s', but there are no rules for that state.",
+ $key,
+ $state,
+ $class,
+ $next_state));
}
}
@@ -236,8 +271,10 @@
if (!$match_length) {
if ($next_state === null) {
throw new UnexpectedValueException(
- "Rule '{$regexp}' matched a zero-length token and causes no ".
- "state transition.");
+ pht(
+ "Rule '%s' matched a zero-length token and causes no ".
+ "state transition.",
+ $regexp));
}
} else {
$position += $match_length;
@@ -250,13 +287,13 @@
} else if ($copt == 'pop') {
if (empty($context)) {
throw new UnexpectedValueException(
- "Rule '{$regexp}' popped empty context!");
+ pht("Rule '%s' popped empty context!", $regexp));
}
$token[] = array_pop($context);
} else if ($copt == 'discard') {
if (empty($context)) {
throw new UnexpectedValueException(
- "Rule '{$regexp}' discarded empty context!");
+ pht("Rule '%s' discarded empty context!", $regexp));
}
array_pop($context);
$token[] = null;
@@ -272,7 +309,7 @@
array_pop($states);
if (empty($states)) {
throw new UnexpectedValueException(
- "Rule '{$regexp}' popped off the last state.");
+ pht("Rule '%s' popped off the last state.", $regexp));
}
} else {
$states[] = $next_state;
@@ -283,7 +320,7 @@
}
throw new UnexpectedValueException(
- "No lexer rule matched input at char {$position}.");
+ pht('No lexer rule matched input at char %d.', $position));
}
$this->lastState = $states;
diff --git a/src/lexer/__tests__/PhutilPHPFragmentLexerTestCase.php b/src/lexer/__tests__/PhutilPHPFragmentLexerTestCase.php
--- a/src/lexer/__tests__/PhutilPHPFragmentLexerTestCase.php
+++ b/src/lexer/__tests__/PhutilPHPFragmentLexerTestCase.php
@@ -309,7 +309,7 @@
$this->assertEqual(null, $caught);
break;
default:
- throw new Exception("No assertion block for test '{$file}'!");
+ throw new Exception(pht("No assertion block for test '%s'!", $file));
}
}
diff --git a/src/lexer/__tests__/PhutilShellLexerTestCase.php b/src/lexer/__tests__/PhutilShellLexerTestCase.php
--- a/src/lexer/__tests__/PhutilShellLexerTestCase.php
+++ b/src/lexer/__tests__/PhutilShellLexerTestCase.php
@@ -200,7 +200,7 @@
$file);
break;
default:
- throw new Exception("No assertion block for test '{$file}'!");
+ throw new Exception(pht("No assertion block for test '%s'!", $file));
}
}
diff --git a/src/markup/__tests__/PhutilSafeHTMLTestCase.php b/src/markup/__tests__/PhutilSafeHTMLTestCase.php
--- a/src/markup/__tests__/PhutilSafeHTMLTestCase.php
+++ b/src/markup/__tests__/PhutilSafeHTMLTestCase.php
@@ -4,7 +4,7 @@
public function testOperator() {
if (!extension_loaded('operator')) {
- $this->assertSkipped('Operator extension not available.');
+ $this->assertSkipped(pht('Operator extension not available.'));
}
$a = phutil_tag('a');
diff --git a/src/markup/engine/PhutilRemarkupEngine.php b/src/markup/engine/PhutilRemarkupEngine.php
--- a/src/markup/engine/PhutilRemarkupEngine.php
+++ b/src/markup/engine/PhutilRemarkupEngine.php
@@ -103,7 +103,7 @@
public function popState($state) {
if (empty($this->states[$state])) {
- throw new Exception("State '{$state}' pushed more than popped!");
+ throw new Exception(pht("State '%s' pushed more than popped!", $state));
}
$this->states[$state]--;
if (!$this->states[$state]) {
@@ -183,7 +183,7 @@
}
if ($starting_cursor === $cursor) {
- throw new Exception('Block in text did not match any block rule.');
+ throw new Exception(pht('Block in text did not match any block rule.'));
}
}
diff --git a/src/markup/engine/__tests__/PhutilRemarkupEngineTestCase.php b/src/markup/engine/__tests__/PhutilRemarkupEngineTestCase.php
--- a/src/markup/engine/__tests__/PhutilRemarkupEngineTestCase.php
+++ b/src/markup/engine/__tests__/PhutilRemarkupEngineTestCase.php
@@ -53,7 +53,7 @@
$this->assertEqual(
$expected_output,
$actual_output,
- "Failed to markup HTML in file '{$file}'.");
+ pht("Failed to markup HTML in file '%s'.", $file));
$engine->setMode(PhutilRemarkupEngine::MODE_TEXT);
$actual_output = (string)$engine->markupText($input_remarkup);
@@ -61,7 +61,7 @@
$this->assertEqual(
$expected_text,
$actual_output,
- "Failed to markup text in file '{$file}'.");
+ pht("Failed to markup text in file '%s'.", $file));
}
private function buildNewTestEngine() {
diff --git a/src/markup/engine/remarkup/blockrule/PhutilRemarkupTableBlockRule.php b/src/markup/engine/remarkup/blockrule/PhutilRemarkupTableBlockRule.php
--- a/src/markup/engine/remarkup/blockrule/PhutilRemarkupTableBlockRule.php
+++ b/src/markup/engine/remarkup/blockrule/PhutilRemarkupTableBlockRule.php
@@ -27,7 +27,7 @@
if (!preg_match('@^<table>(.*)</table>$@si', $text, $matches)) {
return $this->fail(
$text,
- 'Bad table (expected <table>...</table>)');
+ pht('Bad table (expected %s)', '<table>...</table>'));
}
$body = $matches[1];
@@ -39,14 +39,14 @@
if (!preg_match('@^'.$row_fragment.'+$@Usi', $body)) {
return $this->fail(
$body,
- 'Bad table syntax (expected rows <tr>...</tr>)');
+ pht('Bad table syntax (expected rows %s)', '<tr>...</tr>'));
}
// Capture the rows.
$row_regex = '@'.$row_fragment.'@Usi';
if (!preg_match_all($row_regex, $body, $matches, PREG_SET_ORDER)) {
throw new Exception(
- 'Bug in Remarkup tables, parsing fails for input: '.$text);
+ pht('Bug in Remarkup tables, parsing fails for input: %s', $text));
}
$out_rows = array();
@@ -59,14 +59,14 @@
if (!preg_match('@^'.$cell_fragment.'+$@Usi', $content)) {
return $this->fail(
$content,
- 'Bad table syntax (expected cells <td>...</td>)');
+ pht('Bad table syntax (expected cells %s)', '<td>...</td>'));
}
// Capture the cells.
$cell_regex = '@'.$cell_fragment.'@Usi';
if (!preg_match_all($cell_regex, $content, $matches, PREG_SET_ORDER)) {
throw new Exception(
- 'Bug in Remarkup tables, parsing fails for input: '.$text);
+ pht('Bug in Remarkup tables, parsing fails for input: %s', $text));
}
$out_cells = array();
diff --git a/src/markup/render.php b/src/markup/render.php
--- a/src/markup/render.php
+++ b/src/markup/render.php
@@ -68,10 +68,11 @@
if (preg_match('/^javascript:/i', $normalized_href)) {
throw new Exception(
pht(
- "Attempting to render a tag with an 'href' attribute that ".
- "begins with 'javascript:'. This is either a serious security ".
- "concern or a serious architecture concern. Seek urgent ".
- "remedy."));
+ "Attempting to render a tag with an '%s' attribute that begins ".
+ "with '%s'. This is either a serious security concern or a ".
+ "serious architecture concern. Seek urgent remedy.",
+ 'href',
+ 'javascript:'));
}
}
}
@@ -141,11 +142,13 @@
assert_stringlike($result);
return phutil_escape_html((string)$result);
} catch (Exception $ex) {
- $class = get_class($string);
throw new Exception(
- "Object (of class '{$class}') implements ".
- "PhutilSafeHTMLProducerInterface but did not return anything ".
- "renderable from producePhutilSafeHTML().");
+ pht(
+ "Object (of class '%s') implements %s but did not return anything ".
+ "renderable from %s.",
+ get_class($string),
+ 'PhutilSafeHTMLProducerInterface',
+ 'producePhutilSafeHTML()'));
}
}
} else if (is_array($string)) {
diff --git a/src/markup/syntax/engine/__tests__/PhutilDefaultSyntaxHighlighterEngineTestCase.php b/src/markup/syntax/engine/__tests__/PhutilDefaultSyntaxHighlighterEngineTestCase.php
--- a/src/markup/syntax/engine/__tests__/PhutilDefaultSyntaxHighlighterEngineTestCase.php
+++ b/src/markup/syntax/engine/__tests__/PhutilDefaultSyntaxHighlighterEngineTestCase.php
@@ -18,7 +18,10 @@
$engine = new PhutilDefaultSyntaxHighlighterEngine();
foreach ($names as $path => $language) {
$detect = $engine->getLanguageFromFilename($path);
- $this->assertEqual($language, $detect, 'Language detect for '.$path);
+ $this->assertEqual(
+ $language,
+ $detect,
+ pht('Language detect for %s', $path));
}
}
diff --git a/src/markup/syntax/highlighter/__tests__/PhutilXHPASTSyntaxHighlighterTestCase.php b/src/markup/syntax/highlighter/__tests__/PhutilXHPASTSyntaxHighlighterTestCase.php
--- a/src/markup/syntax/highlighter/__tests__/PhutilXHPASTSyntaxHighlighterTestCase.php
+++ b/src/markup/syntax/highlighter/__tests__/PhutilXHPASTSyntaxHighlighterTestCase.php
@@ -17,15 +17,15 @@
$this->assertEqual(
$this->read('builtin-classname.expect'),
(string)$this->highlight($this->read('builtin-classname.source')),
- 'Builtin classnames should not be marked as linkable symbols.');
+ pht('Builtin classnames should not be marked as linkable symbols.'));
$this->assertEqual(
$this->read('trailing-comment.expect'),
(string)$this->highlight($this->read('trailing-comment.source')),
- 'Trailing comments should not be dropped.');
+ pht('Trailing comments should not be dropped.'));
$this->assertEqual(
$this->read('multiline-token.expect'),
(string)$this->highlight($this->read('multiline-token.source')),
- 'Multi-line tokens should be split across lines.');
+ pht('Multi-line tokens should be split across lines.'));
}
}
diff --git a/src/moduleutils/PhutilBootloader.php b/src/moduleutils/PhutilBootloader.php
--- a/src/moduleutils/PhutilBootloader.php
+++ b/src/moduleutils/PhutilBootloader.php
@@ -36,8 +36,10 @@
public function registerLibrary($name, $path) {
if (basename($path) != '__phutil_library_init__.php') {
throw new PhutilBootloaderException(
- 'Only directories with a __phutil_library_init__.php file may be '.
- 'registered as libphutil libraries.');
+ pht(
+ 'Only directories with a %s file may be registered as %s libraries.',
+ '__phutil_library_init__.php',
+ 'libphutil'));
}
$path = dirname($path);
@@ -119,7 +121,9 @@
$okay = include $root.'/__phutil_library_map__.php';
if (!$okay) {
throw new PhutilBootloaderException(
- "Include of '{$root}/__phutil_library_map__.php' failed!");
+ pht(
+ "Include of '%s' failed!",
+ "{$root}/__phutil_library_map__.php"));
}
}
@@ -133,7 +137,7 @@
switch ($version) {
case 1:
throw new Exception(
- 'libphutil v1 libraries are no longer supported.');
+ pht('libphutil v1 libraries are no longer supported.'));
case 2:
// NOTE: In version 2 of the library format, all parents (both
// classes and interfaces) are stored in the 'xmap'. The value is
@@ -146,7 +150,8 @@
}
break;
default:
- throw new Exception("Unsupported library version '{$version}'!");
+ throw new Exception(
+ pht("Unsupported library version '%s'!", $version));
}
}
@@ -177,7 +182,7 @@
public function getLibraryRoot($name) {
if (empty($this->registeredLibraries[$name])) {
throw new PhutilBootloaderException(
- "The phutil library '{$name}' has not been loaded!");
+ pht("The %s library '%s' has not been loaded!", 'phutil', $name));
}
return $this->registeredLibraries[$name];
}
@@ -196,7 +201,7 @@
$okay = $this->executeInclude($root.$path.'/__phutil_library_init__.php');
if (!$okay) {
throw new PhutilBootloaderException(
- "Include of '{$path}/__phutil_library_init__.php' failed!");
+ pht("Include of '%s' failed!", "{$path}/__phutil_library_init__.php"));
}
}
@@ -204,7 +209,8 @@
$path = $this->getLibraryRoot($library).'/'.$source;
$okay = $this->executeInclude($path);
if (!$okay) {
- throw new PhutilBootloaderException("Include of '{$path}' failed!");
+ throw new PhutilBootloaderException(
+ pht("Include of '%s' failed!", $path));
}
}
@@ -227,7 +233,7 @@
$ok = $this->executeInclude($path);
if (!$ok) {
throw new PhutilBootloaderException(
- "Include of extension file '{$path}' failed!");
+ pht("Include of extension file '%s' failed!", $path));
}
$new_functions = get_defined_functions();
diff --git a/src/moduleutils/PhutilLibraryConflictException.php b/src/moduleutils/PhutilLibraryConflictException.php
--- a/src/moduleutils/PhutilLibraryConflictException.php
+++ b/src/moduleutils/PhutilLibraryConflictException.php
@@ -42,12 +42,13 @@
$this->oldPath = $old_path;
$this->newPath = $new_path;
- $message = "Library conflict! The library '{$library}' has already been ".
- "loaded (from '{$old_path}') but is now being loaded again ".
- "from a new location ('{$new_path}'). You can not load ".
- "multiple copies of the same library into a program.";
-
- parent::__construct($message);
+ parent::__construct(pht(
+ "Library conflict! The library '%s' has already been loaded (from '%s') ".
+ "but is now being loaded again from a new location ('%s'). You can not ".
+ "load multiple copies of the same library into a program.",
+ $library,
+ $old_path,
+ $new_path));
}
/**
diff --git a/src/moduleutils/PhutilLibraryMapBuilder.php b/src/moduleutils/PhutilLibraryMapBuilder.php
--- a/src/moduleutils/PhutilLibraryMapBuilder.php
+++ b/src/moduleutils/PhutilLibraryMapBuilder.php
@@ -108,7 +108,7 @@
public function buildAndWriteMap() {
$library_map = $this->buildMap();
- $this->log("Writing map...\n");
+ $this->log(pht('Writing map...'));
$this->writeLibraryMap($library_map);
}
@@ -122,7 +122,7 @@
*/
private function log($message) {
if (!$this->quiet) {
- @fwrite(STDERR, $message);
+ @fwrite(STDERR, "%s\n", $message);
}
return $this;
}
@@ -239,7 +239,7 @@
try {
Filesystem::writeFile($cache_file, $json);
} catch (FilesystemException $ex) {
- $this->log("Unable to save the cache!\n");
+ $this->log(pht('Unable to save the cache!'));
}
}
@@ -251,7 +251,7 @@
* @task symbol
*/
public function dropSymbolCache() {
- $this->log("Dropping symbol cache...\n");
+ $this->log(pht('Dropping symbol cache...'));
Filesystem::remove($this->getPathForSymbolCache());
}
@@ -291,7 +291,11 @@
$init = $this->getPathForLibraryInit();
if (!Filesystem::pathExists($init)) {
- throw new Exception("Provided path '{$root}' is not a phutil library.");
+ throw new Exception(
+ pht(
+ "Provided path '%s' is not a %s library.",
+ $root,
+ 'phutil'));
}
$files = id(new FileFinder($root))
@@ -348,9 +352,14 @@
if (!empty($library_map[$lib_type][$symbol])) {
$prior = $library_map[$lib_type][$symbol];
throw new Exception(
- "Definition of {$type} '{$symbol}' in file '{$file}' duplicates ".
- "prior definition in file '{$prior}'. You can not declare the ".
- "same symbol twice.");
+ pht(
+ "Definition of %s '%s' in file '%s' duplicates prior ".
+ "definition in file '%s'. You can not declare the ".
+ "same symbol twice.",
+ $type,
+ $symbol,
+ $file,
+ $prior));
}
$library_map[$lib_type][$symbol] = $file;
}
@@ -419,13 +428,14 @@
*/
private function analyzeLibrary() {
// Identify all the ".php" source files in the library.
- $this->log("Finding source files...\n");
+ $this->log(pht('Finding source files...'));
$source_map = $this->loadSourceFileMap();
- $this->log("Found ".number_format(count($source_map))." files.\n");
+ $this->log(
+ pht('Found %s files.', number_format(count($source_map))));
// Load the symbol cache with existing parsed symbols. This allows us
// to remap libraries quickly by analyzing only changed files.
- $this->log("Loading symbol cache...\n");
+ $this->log(pht('Loading symbol cache...'));
$symbol_cache = $this->loadSymbolCache();
// If the XHPAST binary is not up-to-date, build it now. Otherwise,
@@ -448,14 +458,16 @@
}
$futures[$file] = $this->buildSymbolAnalysisFuture($file);
}
- $this->log("Found ".number_format(count($symbol_map))." files in cache.\n");
+ $this->log(
+ pht('Found %d files in cache.', number_format(count($symbol_map))));
// Run the analyzer on any files which need analysis.
if ($futures) {
$limit = $this->subprocessLimit;
$count = number_format(count($futures));
- $this->log("Analyzing {$count} files with {$limit} subprocesses...\n");
+ $this->log(
+ pht('Analyzing %d files with %d subprocesses...', $count, $limit));
$progress = new PhutilConsoleProgressBar();
if ($this->quiet) {
@@ -488,7 +500,7 @@
$this->writeSymbolCache($symbol_map, $source_map);
// Our map is up to date, so either show it on stdout or write it to disk.
- $this->log("Building library map...\n");
+ $this->log(pht('Building library map...'));
$this->librarySymbolMap = $this->buildLibraryMap($symbol_map);
}
diff --git a/src/object/Phobject.php b/src/object/Phobject.php
--- a/src/object/Phobject.php
+++ b/src/object/Phobject.php
@@ -22,9 +22,8 @@
public function __set($name, $value) {
throw new DomainException(
pht(
- 'Attempt to write to undeclared property %s::%s.',
- get_class($this),
- $name));
+ 'Attempt to write to undeclared property %s.',
+ get_class($this).'::'.$name));
}
public function current() {
@@ -50,8 +49,7 @@
private function throwOnAttemptedIteration() {
throw new DomainException(
pht(
- 'Attempting to iterate an object (of class %s) which is not '.
- 'iterable.',
+ 'Attempting to iterate an object (of class %s) which is not iterable.',
get_class($this)));
}
diff --git a/src/parser/PhutilParserGenerator.php b/src/parser/PhutilParserGenerator.php
--- a/src/parser/PhutilParserGenerator.php
+++ b/src/parser/PhutilParserGenerator.php
@@ -118,28 +118,44 @@
public function getEOFSymbol() {
if ($this->eofSymbol === null) {
- throw new Exception('Call processGrammar() before getEOFSymbol()!');
+ throw new Exception(
+ pht(
+ 'Call %s before %s!',
+ 'processGrammar()',
+ __FUNCTION__.'()'));
}
return $this->eofSymbol;
}
public function getInitSymbol() {
if ($this->initSymbol === null) {
- throw new Exception('Call processGrammar() before getInitSymbol()!');
+ throw new Exception(
+ pht(
+ 'Call %s before %s!',
+ 'processGrammar()',
+ __FUNCTION__.'()'));
}
return $this->initSymbol;
}
public function getEpsilonSymbol() {
if ($this->epsilonSymbol === null) {
- throw new Exception('Call processGrammar() before getEpsilonSymbol()!');
+ throw new Exception(
+ pht(
+ 'Call %s before %s!',
+ 'processGrammar()',
+ __FUNCTION__.'()'));
}
return $this->epsilonSymbol;
}
public function getEndSymbol() {
if ($this->endSymbol === null) {
- throw new Exception('Call processGrammar() before getEndSymbol()!');
+ throw new Exception(
+ pht(
+ 'Call %s before %s!',
+ 'processGrammar()',
+ __FUNCTION__.'()'));
}
return $this->endSymbol;
}
@@ -208,9 +224,12 @@
foreach ($variant as $symbol) {
if (($symbol === null) && count($variant) > 1) {
throw new PhutilInvalidRuleParserGeneratorException(
- "Rule '{$rule_name}' contains a production '{$vkey}' which ".
- "is nonempty but has a null in it. A rule with other symbols ".
- "may not contain null.");
+ pht(
+ "Rule '%s' contains a production '%s' which is ".
+ "nonempty but has a null in it. A rule with other ".
+ "may not contain null.",
+ $rule_name,
+ $vkey));
}
}
}
@@ -238,10 +257,14 @@
}
$production_string = implode(' ', $production);
throw new PhutilUnknownSymbolParserGeneratorException(
- "Symbol '{$symbol}' in production '{$production_name}' ".
- "('{$production_string}') of rule '{$rule}' does not name a rule ".
- "or terminal. Did you misspell a symbol, fail to specify a ".
- "terminal, or forget a rule?");
+ pht(
+ "Symbol '%s' in production '%s' ('%s') of rule '%s' does not ".
+ "name a rule or terminal. Did you misspell a symbol, fail to ".
+ "specify a terminal, or forget a rule?",
+ $symbol,
+ $production_name,
+ $production_string,
+ $rule));
}
}
}
@@ -255,9 +278,12 @@
$start_rule = $this->getStartRule();
if (!$this->isRule($start_rule)) {
throw new PhutilUnknownSymbolParserGeneratorException(
- "Start rule '{$start_rule}' does not appear in the rules for the ".
- "grammar. Use setStartRule() to choose a different start rule, or ".
- "add a rule named '{$start_rule}'.");
+ pht(
+ "Start rule '%s' does not appear in the rules for the grammar. Use ".
+ "%s to choose a different start rule, or add a rule named '%s'.",
+ $start_rule,
+ 'setStartRule()',
+ $start_rule));
}
}
@@ -319,8 +345,9 @@
$missing_terminals = array_keys($missing);
$missing_terminals = implode(', ', $missing_terminals);
throw new PhutilUnreachableTerminalParserGeneratorException(
- 'Some terminals do not appear in any rule: '.
- $missing_terminals);
+ pht(
+ 'Some terminals do not appear in any rule: %s',
+ $missing_terminals));
}
}
@@ -339,8 +366,9 @@
$missing_rules = array_keys($missing);
$missing_rules = implode(', ', $missing_rules);
throw new PhutilUnreachableRuleParserGeneratorException(
- 'Some rules can never be reached from any production: '.
- $missing_rules);
+ pht(
+ 'Some rules can never be reached from any production: %s',
+ $missing_rules));
}
}
@@ -376,8 +404,10 @@
foreach ($this->rules as $rule => $productions) {
if (!$this->isRuleReducible($rule, $reducible)) {
throw new PhutilIrreducibleRuleParserGeneratorException(
- "Rule '{$rule}' can never be reduced: it recurses indefinitely ".
- "and reaches no production of terminals.");
+ pht(
+ "Rule '%s' can never be reduced: it recurses indefinitely ".
+ "and reaches no production of terminals.",
+ $rule));
}
}
}
@@ -706,9 +736,13 @@
if (false) {
throw new Exception(
- "Reduce/reduce conflict: from state '{$state}', when a ".
- "'{$next}' is encountered, it may be reduced in multiple ".
- "ways: {$ways}");
+ pht(
+ "Reduce/reduce conflict: from state '%s', when a ".
+ "'%s' is encountered, it may be reduced in multiple ".
+ "ways: %s",
+ $state,
+ $next,
+ $ways));
}
}
$reduce[$next] = head($reductions);
@@ -723,8 +757,12 @@
if (false) {
$what = $reduce[$next][0];
throw new Exception(
- "Shift/reduce conflict: from state '{$state}', when a '{$next}' ".
- "is encountered, shifting conflicts with reducing '{$what}'.");
+ pht(
+ "Shift/reduce conflict: from state '%s', when a '%s' ".
+ "is encountered, shifting conflicts with reducing '%s'.",
+ $state,
+ $next,
+ $what));
} else {
// Resolve the shift/reduce by shifting.
$reduce = array();
@@ -732,11 +770,11 @@
}
if ($accept && isset($shift[$eof])) {
- throw new Exception('Accept/shift conflict!');
+ throw new Exception(pht('Accept/shift conflict!'));
}
if ($accept && isset($reduce[$eof])) {
- throw new Exception('Accept/reduce conflict!');
+ throw new Exception(pht('Accept/reduce conflict!'));
}
foreach ($reduce as $next => $item) {
@@ -819,8 +857,11 @@
if (!isset($action_table[$state][$next])) {
$expected = implode(', ', array_keys($action_table[$state]));
throw new Exception(
- "Unexpected '{$next}' in state {$state}! Expected: ".
- $expected);
+ pht(
+ "Unexpected '%s' in state %s! Expected: %s",
+ $next,
+ $state,
+ $expected));
}
$action = $action_table[$state][$next];
@@ -864,7 +905,11 @@
*/
public function inspectRules() {
if (!$this->rulesValidated) {
- throw new Exception('Call processGrammar() before inspectRules()!');
+ throw new Exception(
+ pht(
+ 'Call %s before %s!',
+ 'processGrammar()',
+ __FUNCTION__.'()'));
}
return $this->rules;
}
@@ -875,7 +920,11 @@
*/
public function inspectFirstTable() {
if ($this->firstTable === null) {
- throw new Exception('Call processGrammar() before inspectFirstTable()!');
+ throw new Exception(
+ pht(
+ 'Call %s before %s!',
+ 'processGrammar()',
+ __FUNCTION__.'()'));
}
return $this->firstTable;
}
diff --git a/src/parser/PhutilSimpleOptions.php b/src/parser/PhutilSimpleOptions.php
--- a/src/parser/PhutilSimpleOptions.php
+++ b/src/parser/PhutilSimpleOptions.php
@@ -177,7 +177,7 @@
private function normalizeKey($key) {
if (!strlen($key)) {
- throw new Exception('Empty key is invalid!');
+ throw new Exception(pht('Empty key is invalid!'));
}
if (!$this->caseSensitive) {
$key = strtolower($key);
diff --git a/src/parser/PhutilTypeSpec.php b/src/parser/PhutilTypeSpec.php
--- a/src/parser/PhutilTypeSpec.php
+++ b/src/parser/PhutilTypeSpec.php
@@ -361,7 +361,7 @@
}
return $result;
default:
- throw new Exception("Unhandled parser rule '{$rule}'!");
+ throw new Exception(pht("Unhandled parser rule '%s'!", $rule));
}
}
diff --git a/src/parser/__tests__/PhutilDocblockParserTestCase.php b/src/parser/__tests__/PhutilDocblockParserTestCase.php
--- a/src/parser/__tests__/PhutilDocblockParserTestCase.php
+++ b/src/parser/__tests__/PhutilDocblockParserTestCase.php
@@ -111,7 +111,7 @@
$specials);
break;
default:
- throw new Exception("No test case to handle file '{$file}'!");
+ throw new Exception(pht("No test case to handle file '%s'!", $file));
}
}
diff --git a/src/parser/__tests__/PhutilJSONTestCase.php b/src/parser/__tests__/PhutilJSONTestCase.php
--- a/src/parser/__tests__/PhutilJSONTestCase.php
+++ b/src/parser/__tests__/PhutilJSONTestCase.php
@@ -15,7 +15,7 @@
$this->assertEqual(
$expect,
$serializer->encodeFormatted(array('x' => array())),
- 'Empty arrays should serialize as [], not {}.');
+ pht('Empty arrays should serialize as %s, not %s.', '[]', '{}'));
}
}
diff --git a/src/parser/__tests__/PhutilLanguageGuesserTestCase.php b/src/parser/__tests__/PhutilLanguageGuesserTestCase.php
--- a/src/parser/__tests__/PhutilLanguageGuesserTestCase.php
+++ b/src/parser/__tests__/PhutilLanguageGuesserTestCase.php
@@ -16,7 +16,7 @@
$this->assertEqual(
$expect,
PhutilLanguageGuesser::guessLanguage($source),
- "Guessed language for '{$test}'.");
+ pht("Guessed language for '%s'.", $test));
}
}
diff --git a/src/parser/__tests__/PhutilParserGeneratorTestCase.php b/src/parser/__tests__/PhutilParserGeneratorTestCase.php
--- a/src/parser/__tests__/PhutilParserGeneratorTestCase.php
+++ b/src/parser/__tests__/PhutilParserGeneratorTestCase.php
@@ -275,7 +275,7 @@
break;
}
- throw new Exception('Unexpected rule in ET grammar.');
+ throw new Exception(pht('Unexpected rule in ET grammar.'));
}
private function buildABCGenerator() {
diff --git a/src/parser/__tests__/PhutilSimpleOptionsTestCase.php b/src/parser/__tests__/PhutilSimpleOptionsTestCase.php
--- a/src/parser/__tests__/PhutilSimpleOptionsTestCase.php
+++ b/src/parser/__tests__/PhutilSimpleOptionsTestCase.php
@@ -54,7 +54,7 @@
$this->assertEqual(
$expect,
$parser->parse($string),
- "Correct parse of '{$string}'");
+ pht("Correct parse of '%s'", $string));
}
}
@@ -73,7 +73,7 @@
$this->assertEqual(
$expect,
$parser->parse($string),
- "Correct case-sensitive parse of '{$string}'");
+ pht("Correct case-sensitive parse of '%s'", $string));
}
}
@@ -92,7 +92,7 @@
$this->assertEqual(
array(),
$parser->parse($input),
- "Correct failing parse of invalid input: {$input}");
+ pht('Correct failing parse of invalid input: %s', $input));
}
}
@@ -112,7 +112,7 @@
$this->assertEqual(
$expect,
$parser->unparse($dict),
- 'Correct unparse of '.print_r($dict, true));
+ pht('Correct unparse of %s', print_r($dict, true)));
}
$bogus = array(
@@ -130,14 +130,14 @@
}
$this->assertTrue(
$caught instanceof Exception,
- 'Correct throw on unparse of bad input.');
+ pht('Correct throw on unparse of bad input.'));
}
$parser = new PhutilSimpleOptions();
$this->assertEqual(
'a="\\}"',
$parser->unparse(array('a' => '}'), '}'),
- 'Unparse with extra escape.');
+ pht('Unparse with extra escape.'));
}
}
diff --git a/src/parser/argument/PhutilArgumentParser.php b/src/parser/argument/PhutilArgumentParser.php
--- a/src/parser/argument/PhutilArgumentParser.php
+++ b/src/parser/argument/PhutilArgumentParser.php
@@ -157,7 +157,9 @@
if ($val !== null) {
if ($param_name === null) {
throw new PhutilArgumentUsageException(
- "Argument '{$pre}{$arg}' does not take a parameter.");
+ pht(
+ "Argument '%s' does not take a parameter.",
+ "{$pre}{$arg}"));
}
} else {
if ($param_name !== null) {
@@ -167,7 +169,9 @@
$ii++;
} else {
throw new PhutilArgumentUsageException(
- "Argument '{$pre}{$arg}' requires a parameter.");
+ pht(
+ "Argument '%s' requires a parameter.",
+ "{$pre}{$arg}"));
}
} else {
$val = true;
@@ -177,7 +181,9 @@
if (!$spec->getRepeatable()) {
if (array_key_exists($spec->getName(), $this->results)) {
throw new PhutilArgumentUsageException(
- "Argument '{$pre}{$arg}' was provided twice.");
+ pht(
+ "Argument '%s' was provided twice.",
+ "{$pre}{$arg}"));
}
}
@@ -192,8 +198,11 @@
}
throw new PhutilArgumentUsageException(
- "Argument '{$pre}{$arg}' conflicts with argument ".
- "'--{$conflict}'{$reason}");
+ pht(
+ "Argument '%s' conflicts with argument '%s'%s",
+ "{$pre}{$arg}",
+ "--{$conflict}",
+ $reason));
}
}
@@ -246,7 +255,7 @@
if (count($this->argv)) {
$arg = head($this->argv);
throw new PhutilArgumentUsageException(
- "Unrecognized argument '{$arg}'.");
+ pht("Unrecognized argument '%s'.", $arg));
}
if ($this->showHelp) {
@@ -324,12 +333,12 @@
if ($name === null) {
throw new PhutilArgumentSpecificationException(
- 'Workflow has no name!');
+ pht('Workflow has no name!'));
}
if (isset($this->workflows[$name])) {
throw new PhutilArgumentSpecificationException(
- "Two workflows with name '{$name}!");
+ pht("Two workflows with name '%s!", $name));
}
$this->workflows[$name] = $workflow;
@@ -341,8 +350,7 @@
if (isset($this->workflows['help'])) {
$argv = array('help');
} else {
- throw new PhutilArgumentUsageException(
- 'No workflow selected.');
+ throw new PhutilArgumentUsageException(pht('No workflow selected.'));
}
}
@@ -356,12 +364,14 @@
}
sort($workflow_names);
$command_list = implode(', ', $workflow_names);
- $ex_msg =
- "Invalid command '{$flow}'. Valid commands are: {$command_list}.";
+ $ex_msg = pht(
+ "Invalid command '%s'. Valid commands are: %s.",
+ $flow,
+ $command_list);
if (in_array('help', $workflow_names)) {
$bin = basename($this->bin);
- $ex_msg .=
- "\nFor more details on available commands, run `{$bin} help`.";
+ $ex_msg .= "\n".pht(
+ 'For more details on available commands, run `%s`.', "{$bin} help");
}
throw new PhutilArgumentUsageException($ex_msg);
}
@@ -419,13 +429,14 @@
array(
array(
'name' => 'trace',
- 'help' => 'Trace command execution and show service calls.',
+ 'help' => pht('Trace command execution and show service calls.'),
'standard' => true,
),
array(
'name' => 'no-ansi',
- 'help' => 'Disable ANSI terminal codes, printing plain text with '.
- 'no color or style.',
+ 'help' => pht(
+ 'Disable ANSI terminal codes, printing plain text with '.
+ 'no color or style.'),
'conflicts' => array(
'ansi' => null,
),
@@ -433,31 +444,33 @@
),
array(
'name' => 'ansi',
- 'help' => "Use formatting even in environments which probably ".
- "don't support it.",
+ 'help' => pht(
+ "Use formatting even in environments which probably ".
+ "don't support it."),
'standard' => true,
),
array(
'name' => 'xprofile',
'param' => 'profile',
- 'help' => 'Profile script execution and write results to a file.',
+ 'help' => pht(
+ 'Profile script execution and write results to a file.'),
'standard' => true,
),
array(
'name' => 'help',
'short' => 'h',
- 'help' => 'Show this help.',
+ 'help' => pht('Show this help.'),
'standard' => true,
),
array(
'name' => 'show-standard-options',
- 'help' => 'Show every option, including standard options '.
- 'like this one.',
+ 'help' => pht(
+ 'Show every option, including standard options like this one.'),
'standard' => true,
),
array(
'name' => 'recon',
- 'help' => 'Start in remote console mode.',
+ 'help' => pht('Start in remote console mode.'),
'standard' => true,
),
));
@@ -485,7 +498,8 @@
$xprofile = $this->getArg('xprofile');
if ($xprofile) {
if (!function_exists('xhprof_enable')) {
- throw new Exception("To use '--xprofile', you must install XHProf.");
+ throw new Exception(
+ pht("To use '%s', you must install XHProf.", '--xprofile'));
}
xhprof_enable(0);
@@ -514,7 +528,7 @@
public function getArg($name) {
if (empty($this->specs[$name])) {
throw new PhutilArgumentSpecificationException(
- "No specification exists for argument '{$name}'!");
+ pht("No specification exists for argument '%s'!", $name));
}
if (idx($this->results, $name) !== null) {
@@ -552,7 +566,7 @@
$more = array();
if ($this->bin) {
- $out[] = $this->format('**NAME**');
+ $out[] = $this->format('**%s**', pht('NAME'));
$name = $this->indent(6, '**%s**', basename($this->bin));
if ($this->tagline) {
$name .= $this->format(' - '.$this->tagline);
@@ -562,14 +576,14 @@
}
if ($this->synopsis) {
- $out[] = $this->format('**SYNOPSIS**');
+ $out[] = $this->format('**%s**', pht('SYNOPSIS'));
$out[] = $this->indent(6, $this->synopsis);
$out[] = null;
}
if ($this->workflows) {
$has_help = false;
- $out[] = $this->format('**WORKFLOWS**');
+ $out[] = $this->format('**%s**', pht('WORKFLOWS'));
$out[] = null;
$flows = $this->workflows;
ksort($flows);
@@ -582,13 +596,14 @@
$show_details = false);
}
if ($has_help) {
- $more[] = 'Use **help** __command__ for a detailed command reference.';
+ $more[] = pht(
+ 'Use **%s** __command__ for a detailed command reference.', 'help');
}
}
$specs = $this->renderArgumentSpecs($this->specs);
if ($specs) {
- $out[] = $this->format('**OPTION REFERENCE**');
+ $out[] = $this->format('**%s**', pht('OPTION REFERENCE'));
$out[] = null;
$out[] = $specs;
}
@@ -597,7 +612,8 @@
// a quick hint about it.
if (!empty($this->specs['show-standard-options']) &&
!$this->getArg('show-standard-options')) {
- $more[] = 'Use __--show-standard-options__ to show additional options.';
+ $more[] = pht(
+ 'Use __%s__ to show additional options.', '--show-standard-options');
}
$out[] = null;
@@ -624,7 +640,7 @@
if (!$workflow) {
$out[] = $this->indent(
$indent,
- "There is no **{$workflow_name}** workflow.");
+ pht('There is no **%s** workflow.', $workflow_name));
} else {
$out[] = $this->indent($indent, $workflow->getExamples());
$out[] = $this->indent($indent, $workflow->getSynopsis());
@@ -650,7 +666,7 @@
public function printUsageException(PhutilArgumentUsageException $ex) {
fwrite(
STDERR,
- $this->format("**Usage Exception:** %s\n", $ex->getMessage()));
+ $this->format("**%s** %s\n", pht('Usage Exception:'), $ex->getMessage()));
}
@@ -668,8 +684,11 @@
strlen($value) > 1) {
throw new PhutilArgumentUsageException(
- "Argument '{$value}' is unrecognized. Use '--' to indicate the ".
- "end of flags.");
+ pht(
+ "Argument '%s' is unrecognized. Use '%s' to indicate ".
+ "the end of flags.",
+ $value,
+ '--'));
}
}
return array_values($argv);
@@ -694,15 +713,16 @@
if (isset($this->specs[$name])) {
throw new PhutilArgumentSpecificationException(
- "Two argument specifications have the same name ('{$name}').");
+ pht("Two argument specifications have the same name ('%s').", $name));
}
$short = $spec->getShortAlias();
if ($short) {
if (isset($short_map[$short])) {
throw new PhutilArgumentSpecificationException(
- "Two argument specifications have the same short alias ".
- "('{$short}').");
+ pht(
+ "Two argument specifications have the same short alias ('%s').",
+ $short));
}
$short_map[$short] = $spec;
}
@@ -710,8 +730,9 @@
if ($spec->getWildcard()) {
if ($wildcard) {
throw new PhutilArgumentSpecificationException(
- 'Two argument specifications are marked as wildcard arguments. '.
- 'You can have a maximum of one wildcard argument.');
+ pht(
+ 'Two argument specifications are marked as wildcard arguments. '.
+ 'You can have a maximum of one wildcard argument.'));
} else {
$wildcard = $spec;
}
@@ -724,12 +745,14 @@
foreach ($spec->getConflicts() as $conflict => $reason) {
if (empty($this->specs[$conflict])) {
throw new PhutilArgumentSpecificationException(
- "Argument '{$name}' conflicts with unspecified argument ".
- "'{$conflict}'.");
+ pht(
+ "Argument '%s' conflicts with unspecified argument '%s'.",
+ $name,
+ $conflict));
}
if ($conflict == $name) {
throw new PhutilArgumentSpecificationException(
- "Argument '{$name}' conflicts with itself!");
+ pht("Argument '%s' conflicts with itself!", $name));
}
}
}
diff --git a/src/parser/argument/PhutilArgumentSpecification.php b/src/parser/argument/PhutilArgumentSpecification.php
--- a/src/parser/argument/PhutilArgumentSpecification.php
+++ b/src/parser/argument/PhutilArgumentSpecification.php
@@ -56,8 +56,11 @@
foreach ($unrecognized as $key => $ignored) {
throw new PhutilArgumentSpecificationException(
- "Unrecognized key '{$key}' in argument specification. Recognized keys ".
- "are: ".implode(', ', $recognized_keys).'.');
+ pht(
+ "Unrecognized key '%s' in argument specification. Recognized keys ".
+ "are: %s.",
+ $key,
+ implode(', ', $recognized_keys)));
}
$obj = new PhutilArgumentSpecification();
@@ -118,8 +121,10 @@
private static function validateName($name) {
if (!preg_match('/^[a-z0-9][a-z0-9-]*$/', $name)) {
throw new PhutilArgumentSpecificationException(
- "Argument names may only contain a-z, 0-9 and -, and must be ".
- "at least one character long. '{$name}' is invalid.");
+ pht(
+ "Argument names may only contain a-z, 0-9 and -, and must be ".
+ "at least one character long. '%s' is invalid.",
+ $name));
}
}
@@ -145,13 +150,17 @@
private static function validateShortAlias($alias) {
if (strlen($alias) !== 1) {
throw new PhutilArgumentSpecificationException(
- "Argument short aliases must be exactly one character long. ".
- "'{$alias}' is invalid.");
+ pht(
+ "Argument short aliases must be exactly one character long. ".
+ "'%s' is invalid.",
+ $alias));
}
if (!preg_match('/^[a-zA-Z0-9]$/', $alias)) {
throw new PhutilArgumentSpecificationException(
- "Argument short aliases may only be in a-z, A-Z and 0-9. ".
- "'{$alias}' is invalid.");
+ pht(
+ "Argument short aliases may only be in a-z, A-Z and 0-9. ".
+ "'%s' is invalid.",
+ $alias));
}
}
@@ -228,29 +237,30 @@
public function validate() {
if ($this->name === null) {
throw new PhutilArgumentSpecificationException(
- "Argument specification MUST have a 'name'.");
+ pht("Argument specification MUST have a 'name'."));
}
if ($this->getWildcard()) {
if ($this->getParamName()) {
throw new PhutilArgumentSpecificationException(
- 'Wildcard arguments may not specify a parameter.');
+ pht('Wildcard arguments may not specify a parameter.'));
}
if ($this->getRepeatable()) {
throw new PhutilArgumentSpecificationException(
- 'Wildcard arguments may not be repeatable.');
+ pht('Wildcard arguments may not be repeatable.'));
}
}
if ($this->default !== null) {
if ($this->getRepeatable()) {
throw new PhutilArgumentSpecificationException(
- 'Repeatable arguments may not have a default (always array() for '.
- 'arguments which accept a parameter, or 0 for arguments which do '.
- 'not).');
+ pht(
+ 'Repeatable arguments may not have a default (always array() for '.
+ 'arguments which accept a parameter, or 0 for arguments which do '.
+ 'not).'));
} else if ($this->getParamName() === null) {
throw new PhutilArgumentSpecificationException(
- 'Flag arguments may not have a default (always false).');
+ pht('Flag arguments may not have a default (always false).'));
}
}
}
diff --git a/src/parser/argument/__tests__/PhutilArgumentSpecificationTestCase.php b/src/parser/argument/__tests__/PhutilArgumentSpecificationTestCase.php
--- a/src/parser/argument/__tests__/PhutilArgumentSpecificationTestCase.php
+++ b/src/parser/argument/__tests__/PhutilArgumentSpecificationTestCase.php
@@ -58,7 +58,7 @@
$this->assertEqual(
!$valid,
$caught instanceof Exception,
- "Arg alias '{$alias}'.");
+ pht("Arg alias '%s'.", $alias));
}
}
@@ -134,7 +134,7 @@
$this->assertEqual(
!$expect,
$caught instanceof Exception,
- 'Spec validity for: '.print_r($spec, true));
+ pht('Spec validity for: %s', print_r($spec, true)));
}
}
}
diff --git a/src/parser/argument/workflow/PhutilArgumentWorkflow.php b/src/parser/argument/workflow/PhutilArgumentWorkflow.php
--- a/src/parser/argument/workflow/PhutilArgumentWorkflow.php
+++ b/src/parser/argument/workflow/PhutilArgumentWorkflow.php
@@ -164,7 +164,7 @@
}
public function execute(PhutilArgumentParser $args) {
- throw new Exception("This workflow isn't executable!");
+ throw new Exception(pht("This workflow isn't executable!"));
}
/**
diff --git a/src/parser/argument/workflow/PhutilHelpArgumentWorkflow.php b/src/parser/argument/workflow/PhutilHelpArgumentWorkflow.php
--- a/src/parser/argument/workflow/PhutilHelpArgumentWorkflow.php
+++ b/src/parser/argument/workflow/PhutilHelpArgumentWorkflow.php
@@ -33,8 +33,8 @@
} else {
foreach ($with as $thing) {
echo phutil_console_format(
- "**%s WORKFLOW**\n\n",
- strtoupper($thing));
+ "**%s**\n\n",
+ pht('%s WORKFLOW', strtoupper($thing)));
echo $args->renderWorkflowHelp($thing, $show_flags = true);
echo "\n";
}
diff --git a/src/parser/xhpast/__tests__/PHPASTParserTestCase.php b/src/parser/xhpast/__tests__/PHPASTParserTestCase.php
--- a/src/parser/xhpast/__tests__/PHPASTParserTestCase.php
+++ b/src/parser/xhpast/__tests__/PHPASTParserTestCase.php
@@ -7,7 +7,8 @@
try {
PhutilXHPASTBinary::build();
} catch (Exception $ex) {
- $this->assertSkipped(pht('xhpast is not built or not up to date.'));
+ $this->assertSkipped(
+ pht('%s is not built or not up to date.', 'xhpast'));
}
}
diff --git a/src/parser/xhpast/api/XHPASTTree.php b/src/parser/xhpast/api/XHPASTTree.php
--- a/src/parser/xhpast/api/XHPASTTree.php
+++ b/src/parser/xhpast/api/XHPASTTree.php
@@ -57,7 +57,8 @@
}
throw new Exception(
pht(
- 'XHPAST failed to parse file data %d: %s',
+ '%s failed to parse file data %d: %s',
+ 'XHPAST',
$err,
$stderr));
}
@@ -67,7 +68,7 @@
$data = phutil_json_decode($stdout);
} catch (PhutilJSONParserException $ex) {
throw new PhutilProxyException(
- pht('XHPAST: failed to decode tree.'),
+ pht('%s: failed to decode tree.', 'XHPAST'),
$ex);
}
diff --git a/src/parser/xhpast/bin/PhutilXHPASTBinary.php b/src/parser/xhpast/bin/PhutilXHPASTBinary.php
--- a/src/parser/xhpast/bin/PhutilXHPASTBinary.php
+++ b/src/parser/xhpast/bin/PhutilXHPASTBinary.php
@@ -44,7 +44,7 @@
// Test the binary.
if (!self::isAvailable()) {
- throw new Exception(pht('xhpast is broken.'));
+ throw new Exception(pht('%s is broken.', 'xhpast'));
}
self::$version = null;
@@ -63,7 +63,7 @@
"%s:\n\n \$ %s\n",
pht(
"Your version of '%s' is unbuilt or out of date. Run this ".
- "script to build it",
+ "script to build it.",
'xhpast'),
$make);
}
diff --git a/src/phage/agent/PhagePHPAgent.php b/src/phage/agent/PhagePHPAgent.php
--- a/src/phage/agent/PhagePHPAgent.php
+++ b/src/phage/agent/PhagePHPAgent.php
@@ -48,7 +48,7 @@
$open = $channel->update();
if (!$open) {
- throw new Exception('Channel closed!');
+ throw new Exception(pht('Channel closed!'));
}
while (true) {
diff --git a/src/phage/bootloader/PhagePHPAgentBootloader.php b/src/phage/bootloader/PhagePHPAgentBootloader.php
--- a/src/phage/bootloader/PhagePHPAgentBootloader.php
+++ b/src/phage/bootloader/PhagePHPAgentBootloader.php
@@ -82,7 +82,7 @@
$boot_sequence->addText($main_sequence->toString());
if (strlen($boot_length) > 8192) {
- throw new Exception('Stage 1 bootloader is too large!');
+ throw new Exception(pht('Stage 1 bootloader is too large!'));
}
$this->bootSequence = $boot_sequence;
diff --git a/src/phage/util/PhutilBallOfPHP.php b/src/phage/util/PhutilBallOfPHP.php
--- a/src/phage/util/PhutilBallOfPHP.php
+++ b/src/phage/util/PhutilBallOfPHP.php
@@ -12,7 +12,10 @@
$data = Filesystem::readFile($path);
if (strncmp($data, "<?php\n", 6)) {
throw new Exception(
- "Expected file '{$path}' to begin \"<?php\\n\".");
+ pht(
+ "Expected file '%s' to begin `%s`.",
+ $path,
+ '<?php\n'));
}
$this->parts[] = substr($data, 6);
return $this;
diff --git a/src/sprites/PhutilSprite.php b/src/sprites/PhutilSprite.php
--- a/src/sprites/PhutilSprite.php
+++ b/src/sprites/PhutilSprite.php
@@ -67,7 +67,7 @@
public function getSourceFile($scale) {
if (empty($this->sourceFiles[$scale])) {
- throw new Exception("No source file for scale '{$scale}'!");
+ throw new Exception(pht("No source file for scale '%s'!", $scale));
}
return $this->sourceFiles[$scale];
diff --git a/src/sprites/PhutilSpriteSheet.php b/src/sprites/PhutilSpriteSheet.php
--- a/src/sprites/PhutilSpriteSheet.php
+++ b/src/sprites/PhutilSpriteSheet.php
@@ -78,7 +78,9 @@
$width = $sprite->getSourceW();
} else if ($width !== $sprite->getSourceW()) {
throw new Exception(
- "All sprites in a 'repeat-x' sheet must have the same width.");
+ pht(
+ "All sprites in a '%s' sheet must have the same width.",
+ 'repeat-x'));
}
}
break;
@@ -92,12 +94,14 @@
$height = $sprite->getSourceH();
} else if ($height !== $sprite->getSourceH()) {
throw new Exception(
- "All sprites in a 'repeat-y' sheet must have the same height.");
+ pht(
+ "All sprites in a '%s' sheet must have the same height.",
+ 'repeat-y'));
}
}
break;
default:
- throw new Exception("Unknown sprite sheet type '{$type}'!");
+ throw new Exception(pht("Unknown sprite sheet type '%s'!", $type));
}
@@ -247,14 +251,14 @@
public function generateImage($path, $scale = 1) {
$this->generate();
- $this->log("Writing sprite '{$path}'...");
+ $this->log(pht("Writing sprite '%s'...", $path));
imagepng($this->images[$scale], $path);
return $this;
}
public function generateCSS($path) {
$this->generate();
- $this->log("Writing CSS '{$path}'...");
+ $this->log(pht("Writing CSS '%s'...", $path));
$out = $this->css;
$out = str_replace('{X}', imagesx($this->images[1]), $out);
@@ -357,16 +361,22 @@
$i_w = $this->sources[$file]['x'];
if ($s_w > $i_w) {
throw new Exception(
- "Sprite source for '{$file}' is too small (expected width {$s_w}, ".
- "found {$i_w}).");
+ pht(
+ "Sprite source for '%s' is too small (expected width %d, found %d).",
+ $file,
+ $s_w,
+ $i_w));
}
$s_h = $sprite->getSourceH() * $scale;
$i_h = $this->sources[$file]['y'];
if ($s_h > $i_h) {
throw new Exception(
- "Sprite source for '{$file}' is too small (expected height {$s_h}, ".
- "found {$i_h}).");
+ pht(
+ "Sprite source for '%s' is too small (expected height %d, found %d).",
+ $file,
+ $s_h,
+ $i_h));
}
return $this->sources[$file]['image'];
diff --git a/src/symbols/PhutilSymbolLoader.php b/src/symbols/PhutilSymbolLoader.php
--- a/src/symbols/PhutilSymbolLoader.php
+++ b/src/symbols/PhutilSymbolLoader.php
@@ -371,11 +371,11 @@
$load_failed = null;
if ($is_function) {
if (!function_exists($name)) {
- $load_failed = 'function';
+ $load_failed = pht('function');
}
} else {
if (!class_exists($name, false) && !interface_exists($name, false)) {
- $load_failed = 'class or interface';
+ $load_failed = pht('class or interface');
}
}
@@ -384,9 +384,15 @@
throw new PhutilMissingSymbolException(
$name,
$load_failed,
- "the symbol map for library '{$lib_name}' (at '{$lib_path}') claims ".
- "this {$load_failed} is defined in '{$where}', but loading that ".
- "source file did not cause the {$load_failed} to become defined.");
+ pht(
+ "the symbol map for library '%s' (at '%s') claims this %s is ".
+ "defined in '%s', but loading that source file did not cause the ".
+ "%s to become defined.",
+ $lib_name,
+ $lib_path,
+ $load_failed,
+ $where,
+ $load_failed));
}
}
diff --git a/src/symbols/exception/PhutilMissingSymbolException.php b/src/symbols/exception/PhutilMissingSymbolException.php
--- a/src/symbols/exception/PhutilMissingSymbolException.php
+++ b/src/symbols/exception/PhutilMissingSymbolException.php
@@ -4,12 +4,17 @@
public function __construct($symbol, $type, $reason) {
parent::__construct(
- "Failed to load {$type} '{$symbol}': $reason ".
- "If this symbol was recently added or moved, your library map may ".
- "be out of date. You can rebuild the map by running 'arc liberate'. ".
- "For more information, see: ".
- "http://www.phabricator.com/docs/phabricator/article/".
- "libphutil_Libraries_User_Guide.html");
+ pht(
+ "Failed to load %s '%s': %s ".
+ "If this symbol was recently added or moved, your library map may ".
+ "be out of date. You can rebuild the map by running '%s'. ".
+ "For more information, see: %s",
+ $type,
+ $symbol,
+ $reason,
+ 'arc liberate',
+ 'http://www.phabricator.com/docs/phabricator/article/'.
+ 'libphutil_Libraries_User_Guide.html'));
}
}
diff --git a/src/utils/AbstractDirectedGraph.php b/src/utils/AbstractDirectedGraph.php
--- a/src/utils/AbstractDirectedGraph.php
+++ b/src/utils/AbstractDirectedGraph.php
@@ -75,8 +75,11 @@
final public function addNodes(array $nodes) {
if ($this->graphLoaded) {
throw new Exception(
- 'Call addNodes() before calling loadGraph(). You can not add more '.
- 'nodes once you have loaded the graph.');
+ pht(
+ 'Call %s before calling %s. You can not add more nodes '.
+ 'once you have loaded the graph.',
+ __FUNCTION__.'()',
+ 'loadGraph()'));
}
$this->knownNodes += $nodes;
@@ -237,8 +240,10 @@
foreach ($load as $node) {
if (!isset($new_nodes[$node]) || !is_array($new_nodes[$node])) {
throw new Exception(
- 'loadEdges() must return an edge list array for each provided '.
- 'node, or the cycle detection algorithm may not terminate.');
+ pht(
+ '%s must return an edge list array for each provided '.
+ 'node, or the cycle detection algorithm may not terminate.',
+ 'loadEdges()'));
}
}
@@ -281,13 +286,17 @@
final public function detectCycles($node) {
if (!$this->graphLoaded) {
throw new Exception(
- 'Call loadGraph() to build the graph out before calling '.
- 'detectCycles().');
+ pht(
+ 'Call %s to build the graph out before calling %s.',
+ 'loadGraph()',
+ __FUNCTION__.'()'));
}
if (!isset($this->knownNodes[$node])) {
throw new Exception(
- "The node '{$node}' is not known. Call addNodes() to seed the graph ".
- "with nodes.");
+ pht(
+ "The node '%s' is not known. Call %s to seed the graph with nodes.",
+ $node,
+ 'addNodes()'));
}
$visited = array();
diff --git a/src/utils/PhutilCallbackFilterIterator.php b/src/utils/PhutilCallbackFilterIterator.php
--- a/src/utils/PhutilCallbackFilterIterator.php
+++ b/src/utils/PhutilCallbackFilterIterator.php
@@ -1,7 +1,7 @@
<?php
/**
- * NOTE: This class has the same purpose as CallbackFilterIterator in PHP 5.4.
+ * NOTE: This class has the same purpose as `CallbackFilterIterator` in PHP 5.4.
*/
final class PhutilCallbackFilterIterator extends FilterIterator {
private $callback;
@@ -13,7 +13,7 @@
public function __construct(Iterator $iterator, $callback) {
parent::__construct($iterator);
if (!is_callable($callback)) {
- throw new Exception('Callback must be callable.');
+ throw new Exception(pht('Callback must be callable.'));
}
$this->callback = $callback;
}
diff --git a/src/utils/PhutilDirectedScalarGraph.php b/src/utils/PhutilDirectedScalarGraph.php
--- a/src/utils/PhutilDirectedScalarGraph.php
+++ b/src/utils/PhutilDirectedScalarGraph.php
@@ -8,8 +8,10 @@
protected function loadEdges(array $nodes) {
throw new Exception(
- 'PhutilDirectedScalarGraph can not load additional nodes at runtime. '.
- 'Tried to load: '.implode(', ', $nodes));
+ pht(
+ '%s can not load additional nodes at runtime. Tried to load: %s',
+ __CLASS__,
+ implode(', ', $nodes)));
}
}
diff --git a/src/utils/PhutilEditDistanceMatrix.php b/src/utils/PhutilEditDistanceMatrix.php
--- a/src/utils/PhutilEditDistanceMatrix.php
+++ b/src/utils/PhutilEditDistanceMatrix.php
@@ -166,7 +166,7 @@
private function requireSequences() {
if ($this->x === null) {
throw new Exception(
- 'Call setSequences() before performing useful work!');
+ pht('Call %s before performing useful work!', 'setSequences()'));
}
}
@@ -267,7 +267,7 @@
} else if ($type == 'd') {
$xx -= 1;
} else {
- throw new Exception("Unknown type '{$type}' in type matrix.");
+ throw new Exception(pht("Unknown type '%s' in type matrix.", $type));
}
$str .= $chr;
@@ -293,7 +293,7 @@
private function getTypeMatrix() {
if (!$this->computeString) {
throw new Exception(
- 'Call setComputeString() before getTypeMatrix().');
+ pht('Call %s before %s.', 'setComputeString()', 'getTypeMatrix()'));
}
if ($this->typeMatrix === null) {
$this->computeMatrix($this->x, $this->y);
@@ -366,8 +366,11 @@
$alt_cost = $this->getAlterCost();
if ($alt_cost && !$use_types) {
throw new Exception(
- 'If you provide an alter cost with setAlterCost(), you must enable '.
- 'type computation with setComputeStrings().');
+ pht(
+ 'If you provide an alter cost with %s, you must enable '.
+ 'type computation with %s.',
+ 'setAlterCost()',
+ 'setComputeStrings()'));
}
// Build the edit distance matrix.
diff --git a/src/utils/PhutilSystem.php b/src/utils/PhutilSystem.php
--- a/src/utils/PhutilSystem.php
+++ b/src/utils/PhutilSystem.php
@@ -29,8 +29,10 @@
} else {
throw new Exception(
pht(
- 'Unable to access /proc/meminfo or `vm_stat` on this system to '.
- 'get system memory information.'));
+ 'Unable to access %s or `%s` on this system to '.
+ 'get system memory information.',
+ '/proc/meminfo',
+ 'vm_stat'));
}
}
@@ -72,8 +74,9 @@
if (!array_key_exists($key, $map)) {
throw new Exception(
pht(
- 'Expected to find "%s" in "/proc/meminfo" output, but did not.',
- $key));
+ 'Expected to find "%s" in "%s" output, but did not.',
+ $key,
+ '/proc/meminfo'));
}
}
@@ -121,7 +124,9 @@
if (!$page_size) {
throw new Exception(
pht(
- 'Expected to find "page size" in `vm_stat` output, but did not.'));
+ 'Expected to find "%s" in `%s` output, but did not.',
+ 'page size',
+ 'vm_stat'));
}
$expect = array(
@@ -134,8 +139,9 @@
if (!array_key_exists($key, $map)) {
throw new Exception(
pht(
- 'Expected to find "%s" in `vm_stat` output, but did not.',
- $key));
+ 'Expected to find "%s" in `%s` output, but did not.',
+ $key,
+ 'vm_stat'));
}
}
diff --git a/src/utils/__tests__/AbstractDirectedGraphTestCase.php b/src/utils/__tests__/AbstractDirectedGraphTestCase.php
--- a/src/utils/__tests__/AbstractDirectedGraphTestCase.php
+++ b/src/utils/__tests__/AbstractDirectedGraphTestCase.php
@@ -8,7 +8,7 @@
);
$cycle = $this->findGraphCycle($graph);
- $this->assertEqual(null, $cycle, 'Trivial Graph');
+ $this->assertEqual(null, $cycle, pht('Trivial Graph'));
}
public function testNoncyclicGraph() {
@@ -20,7 +20,7 @@
);
$cycle = $this->findGraphCycle($graph);
- $this->assertEqual(null, $cycle, 'Noncyclic Graph');
+ $this->assertEqual(null, $cycle, pht('Noncyclic Graph'));
}
public function testTrivialCyclicGraph() {
@@ -29,7 +29,7 @@
);
$cycle = $this->findGraphCycle($graph);
- $this->assertEqual(array('A', 'A'), $cycle, 'Trivial Cycle');
+ $this->assertEqual(array('A', 'A'), $cycle, pht('Trivial Cycle'));
}
public function testCyclicGraph() {
@@ -44,7 +44,7 @@
);
$cycle = $this->findGraphCycle($graph);
- $this->assertEqual(array('A', 'C', 'F', 'C'), $cycle, 'Cyclic Graph');
+ $this->assertEqual(array('A', 'C', 'F', 'C'), $cycle, pht('Cyclic Graph'));
}
public function testNonTreeGraph() {
@@ -57,7 +57,7 @@
);
$cycle = $this->findGraphCycle($graph);
- $this->assertEqual(null, $cycle, 'NonTreeGraph');
+ $this->assertEqual(null, $cycle, pht('Non-tree graph'));
}
public function testEdgeLoadFailure() {
@@ -74,7 +74,7 @@
$this->assertTrue(
(bool)$raised,
- 'Exception raised by unloadable edges.');
+ pht('Exception raised by unloadable edges.'));
}
public function testTopographicSortTree() {
@@ -91,7 +91,7 @@
$this->assertEqual(
array('A', 'C', 'B', 'E', 'D'),
$sorted,
- 'Topographically sorted tree.');
+ pht('Topographically sorted tree.'));
$graph = array(
'A' => array('B', 'C'),
@@ -106,7 +106,7 @@
$this->assertEqual(
array('A', 'B', 'C', 'D', 'E'),
$sorted,
- 'Topographically sorted tree with nesting.');
+ pht('Topographically sorted tree with nesting.'));
}
public function testBestEffortTopographicSortTree() {
diff --git a/src/utils/__tests__/PhutilEditDistanceMatrixTestCase.php b/src/utils/__tests__/PhutilEditDistanceMatrixTestCase.php
--- a/src/utils/__tests__/PhutilEditDistanceMatrixTestCase.php
+++ b/src/utils/__tests__/PhutilEditDistanceMatrixTestCase.php
@@ -148,7 +148,11 @@
$this->assertEqual(
$expect,
$cost,
- "Edit distance of '{$x}' -> '{$y}' with costs ({$desc}).");
+ pht(
+ "Edit distance of '%s' -> '%s' with costs (%s).",
+ $x,
+ $y,
+ $desc));
}
private function assertEditString(
@@ -171,7 +175,11 @@
$this->assertEqual(
$expect,
$string,
- "Edit string of '{$x}' -> '{$y}' with costs ({$desc}).");
+ pht(
+ "Edit string of '%s' -> '%s' with costs (%s).",
+ $x,
+ $y,
+ $desc));
}
private function buildMatrix($x, $y, $ins, $del, $rep, $trn, $alt) {
@@ -196,6 +204,4 @@
->setAlterCost($alt);
}
-
-
}
diff --git a/src/utils/__tests__/PhutilUTF8TestCase.php b/src/utils/__tests__/PhutilUTF8TestCase.php
--- a/src/utils/__tests__/PhutilUTF8TestCase.php
+++ b/src/utils/__tests__/PhutilUTF8TestCase.php
@@ -90,7 +90,7 @@
$this->assertEqual(
$expect,
phutil_utf8v_codepoints($str),
- 'Codepoint Vector of '.$str);
+ pht('Codepoint Vector of %s', $str));
}
}
@@ -117,7 +117,7 @@
$this->assertEqual(
$expect,
phutil_utf8_console_strlen($str),
- 'Console Length of '.$str);
+ pht('Console Length of %s', $str));
}
}
@@ -168,7 +168,7 @@
->setMaximumGlyphs($length)
->setTerminator($terminal)
->truncateString($string);
- $this->assertEqual($expect, $result, 'Shortening of '.$string);
+ $this->assertEqual($expect, $result, pht('Shortening of %s', $string));
}
}
@@ -207,19 +207,19 @@
->setMaximumBytes($b_len)
->setTerminator('!')
->truncateString($input);
- $this->assertEqual($b_out, $result, 'byte-short of '.$input);
+ $this->assertEqual($b_out, $result, pht('byte-short of %s', $input));
$result = id(new PhutilUTF8StringTruncator())
->setMaximumCodepoints($p_len)
->setTerminator('!')
->truncateString($input);
- $this->assertEqual($p_out, $result, 'codepoint-short of '.$input);
+ $this->assertEqual($p_out, $result, pht('codepoint-short of %s', $input));
$result = id(new PhutilUTF8StringTruncator())
->setMaximumGlyphs($g_len)
->setTerminator('!')
->truncateString($input);
- $this->assertEqual($g_out, $result, 'glyph-short of '.$input);
+ $this->assertEqual($g_out, $result, pht('glyph-short of %s', $input));
}
}
@@ -281,7 +281,7 @@
$this->assertEqual(
$expect,
phutil_utf8_hard_wrap_html($string, $width),
- "Wrapping of '".$string."'");
+ pht("Wrapping of '%s'.", $string));
}
}
@@ -355,7 +355,7 @@
} catch (Exception $ex) {
$caught = $ex;
}
- $this->assertTrue((bool)$caught, 'Requires source encoding.');
+ $this->assertTrue((bool)$caught, pht('Requires source encoding.'));
$caught = null;
try {
@@ -363,13 +363,13 @@
} catch (Exception $ex) {
$caught = $ex;
}
- $this->assertTrue((bool)$caught, 'Requires target encoding.');
+ $this->assertTrue((bool)$caught, pht('Requires target encoding.'));
}
public function testUTF8Convert() {
if (!function_exists('mb_convert_encoding')) {
- $this->assertSkipped('Requires mbstring extension.');
+ $this->assertSkipped(pht('Requires %s extension.', 'mbstring'));
}
// "[ae]gis se[n]or [(c)] 1970 [+/-] 1 [degree]"
@@ -377,7 +377,7 @@
$expect = "\xC3\xA6gis SE\xC3\x91OR \xC2\xA9 1970 \xC2\xB11\xC2\xB0";
$output = phutil_utf8_convert($input, 'UTF-8', 'ISO-8859-1');
- $this->assertEqual($expect, $output, 'Conversion from ISO-8859-1.');
+ $this->assertEqual($expect, $output, pht('Conversion from ISO-8859-1.'));
$caught = null;
try {
@@ -386,7 +386,7 @@
$caught = $ex;
}
- $this->assertTrue((bool)$caught, 'Conversion with bogus encoding.');
+ $this->assertTrue((bool)$caught, pht('Conversion with bogus encoding.'));
}
diff --git a/src/utils/__tests__/PhutilUtilsTestCase.php b/src/utils/__tests__/PhutilUtilsTestCase.php
--- a/src/utils/__tests__/PhutilUtilsTestCase.php
+++ b/src/utils/__tests__/PhutilUtilsTestCase.php
@@ -178,7 +178,7 @@
$this->assertTrue(
($caught instanceof InvalidArgumentException),
- "array_mergev() invalid on {$key}");
+ pht('%s invalid on %s', 'array_mergev()', $key));
}
}
@@ -371,7 +371,7 @@
$this->assertEqual(
$expect,
phutil_split_lines($input, $retain_endings = true),
- "(Retained) ".addcslashes($input, "\r\n\\"));
+ pht('(Retained) %s', addcslashes($input, "\r\n\\")));
}
$discard_cases = array(
@@ -390,7 +390,7 @@
$this->assertEqual(
$expect,
phutil_split_lines($input, $retain_endings = false),
- "(Discarded) ".addcslashes($input, "\r\n\\"));
+ pht('(Discarded) %s', addcslashes($input, "\r\n\\")));
}
}
diff --git a/src/utils/utf8.php b/src/utils/utf8.php
--- a/src/utils/utf8.php
+++ b/src/utils/utf8.php
@@ -319,7 +319,8 @@
$ii += 1;
continue;
} else if ($byte < "\xC0") {
- throw new Exception('Invalid UTF-8 string passed to phutil_utf8v().');
+ throw new Exception(
+ pht('Invalid UTF-8 string passed to %s.', __FUNCTION__));
} else if ($byte <= "\xDF") {
$seq_len = 2;
} else if ($byte <= "\xEF") {
@@ -331,15 +332,18 @@
} else if ($byte <= "\xFD") {
$seq_len = 6;
} else {
- throw new Exception('Invalid UTF-8 string passed to phutil_utf8v().');
+ throw new Exception(
+ pht('Invalid UTF-8 string passed to %s.', __FUNCTION__));
}
if ($ii + $seq_len > $len) {
- throw new Exception('Invalid UTF-8 string passed to phutil_utf8v().');
+ throw new Exception(
+ pht('Invalid UTF-8 string passed to %s.', __FUNCTION__));
}
for ($jj = 1; $jj < $seq_len; ++$jj) {
if ($string[$ii + $jj] >= "\xC0") {
- throw new Exception('Invalid UTF-8 string passed to phutil_utf8v().');
+ throw new Exception(
+ pht('Invalid UTF-8 string passed to %s.', __FUNCTION__));
}
}
$res[] = substr($string, $ii, $seq_len);
@@ -515,13 +519,15 @@
function phutil_utf8_convert($string, $to_encoding, $from_encoding) {
if (!$from_encoding) {
throw new InvalidArgumentException(
- 'Attempting to convert a string encoding, but no source encoding '.
- 'was provided. Explicitly provide the source encoding.');
+ pht(
+ 'Attempting to convert a string encoding, but no source encoding '.
+ 'was provided. Explicitly provide the source encoding.'));
}
if (!$to_encoding) {
throw new InvalidArgumentException(
- 'Attempting to convert a string encoding, but no target encoding '.
- 'was provided. Explicitly provide the target encoding.');
+ pht(
+ 'Attempting to convert a string encoding, but no target encoding '.
+ 'was provided. Explicitly provide the target encoding.'));
}
// Normalize encoding names so we can no-op the very common case of UTF8
@@ -534,10 +540,14 @@
if (!function_exists('mb_convert_encoding')) {
throw new Exception(
- "Attempting to convert a string encoding from '{$from_encoding}' ".
- "to '{$to_encoding}', but the 'mbstring' PHP extension is not ".
- "available. Install mbstring to work with encodings other than ".
- "UTF-8.");
+ pht(
+ "Attempting to convert a string encoding from '%s' to '%s', ".
+ "but the '%s' PHP extension is not available. Install %s to ".
+ "work with encodings other than UTF-8.",
+ $from_encoding,
+ $to_encoding,
+ 'mbstring',
+ 'mbstring'));
}
$result = @mb_convert_encoding($string, $to_encoding, $from_encoding);
@@ -545,11 +555,14 @@
if ($result === false) {
$message = error_get_last();
if ($message) {
- $message = idx($message, 'message', 'Unknown error.');
+ $message = idx($message, 'message', pht('Unknown error.'));
}
throw new Exception(
- "String conversion from encoding '{$from_encoding}' to encoding ".
- "'{$to_encoding}' failed: {$message}");
+ pht(
+ "String conversion from encoding '%s' to encoding '%s' failed: %s",
+ $from_encoding,
+ $to_encoding,
+ $message));
}
return $result;
diff --git a/src/utils/utils.php b/src/utils/utils.php
--- a/src/utils/utils.php
+++ b/src/utils/utils.php
@@ -420,7 +420,7 @@
*/
function mfilter(array $list, $method, $negate = false) {
if (!is_string($method)) {
- throw new InvalidArgumentException('Argument method is not a string.');
+ throw new InvalidArgumentException(pht('Argument method is not a string.'));
}
$result = array();
@@ -465,7 +465,7 @@
*/
function ifilter(array $list, $index, $negate = false) {
if (!is_scalar($index)) {
- throw new InvalidArgumentException('Argument index is not a scalar.');
+ throw new InvalidArgumentException(pht('Argument index is not a scalar.'));
}
$result = array();
@@ -529,18 +529,23 @@
if (!is_array($object)) {
$given = gettype($object);
throw new InvalidArgumentException(
- "Array item with key '{$key}' must be of type array, ".
- "{$given} given.");
+ pht(
+ "Array item with key '%s' must be of type array, %s given.",
+ $key,
+ $given));
}
} else if (!($object instanceof $class)) {
$given = gettype($object);
if (is_object($object)) {
- $given = 'instance of '.get_class($object);
+ $given = pht('instance of %s', get_class($object));
}
throw new InvalidArgumentException(
- "Array item with key '{$key}' must be an instance of {$class}, ".
- "{$given} given.");
+ pht(
+ "Array item with key '%s' must be an instance of %s, %s given.",
+ $key,
+ $class,
+ $given));
}
}
@@ -576,7 +581,9 @@
}
throw new InvalidArgumentException(
- 'Argument must be scalar or object which implements __toString()!');
+ pht(
+ 'Argument must be scalar or object which implements %s!',
+ '__toString()'));
}
/**
@@ -735,8 +742,9 @@
if (!is_array($item)) {
throw new InvalidArgumentException(
pht(
- 'Expected all items passed to array_mergev() to be arrays, but '.
+ 'Expected all items passed to %s to be arrays, but '.
'argument with key "%s" has type "%s".',
+ __FUNCTION__.'()',
$key,
gettype($item)));
}
@@ -991,7 +999,8 @@
throw new InvalidArgumentException(
pht(
'Unable to parse unit specification (expected a specification in the '.
- 'form "5 days in seconds"): %s',
+ 'form "%s"): %s',
+ '5 days in seconds',
$description));
}
diff --git a/src/utils/viewutils.php b/src/utils/viewutils.php
--- a/src/utils/viewutils.php
+++ b/src/utils/viewutils.php
@@ -102,7 +102,7 @@
$matches = null;
if (!preg_match('/^(?:\d+(?:[.]\d+)?)([kmgtp]?)b?$/i', $bytes, $matches)) {
- throw new Exception("Unable to parse byte size '{$input}'!");
+ throw new Exception(pht("Unable to parse byte size '%s'!", $input));
}
$scale = array(
diff --git a/src/xsprintf/PhutilCommandString.php b/src/xsprintf/PhutilCommandString.php
--- a/src/xsprintf/PhutilCommandString.php
+++ b/src/xsprintf/PhutilCommandString.php
@@ -52,7 +52,7 @@
case self::MODE_POWERSHELL:
return self::escapePowershell($value);
default:
- throw new Exception('Unknown escaping mode!');
+ throw new Exception(pht('Unknown escaping mode!'));
}
}
diff --git a/src/xsprintf/__tests__/PhutilCsprintfTestCase.php b/src/xsprintf/__tests__/PhutilCsprintfTestCase.php
--- a/src/xsprintf/__tests__/PhutilCsprintfTestCase.php
+++ b/src/xsprintf/__tests__/PhutilCsprintfTestCase.php
@@ -59,7 +59,7 @@
public function testEscapingIsRobust() {
if (phutil_is_windows()) {
- $this->assertSkipped("This test doesn't work on Windows.");
+ $this->assertSkipped(pht("This test doesn't work on Windows."));
}
// Escaping should be robust even when used to escape commands which take
diff --git a/src/xsprintf/csprintf.php b/src/xsprintf/csprintf.php
--- a/src/xsprintf/csprintf.php
+++ b/src/xsprintf/csprintf.php
@@ -81,7 +81,7 @@
// Check that the value is a non-empty array.
if (!is_array($value)) {
throw new InvalidArgumentException(
- "Expected an array for %L{$next} conversion.");
+ pht('Expected an array for %%L%s conversion.', $next));
}
switch ($next) {
@@ -119,7 +119,7 @@
case 'P':
if (!($value instanceof PhutilOpaqueEnvelope)) {
throw new InvalidArgumentException(
- 'Expected PhutilOpaqueEnvelope for %P conversion.');
+ pht('Expected %s for %%P conversion.', 'PhutilOpaqueEnvelope'));
}
if ($is_unmasked) {
$value = $value->openEnvelope();
diff --git a/src/xsprintf/exception/XsprintfUnknownConversionException.php b/src/xsprintf/exception/XsprintfUnknownConversionException.php
--- a/src/xsprintf/exception/XsprintfUnknownConversionException.php
+++ b/src/xsprintf/exception/XsprintfUnknownConversionException.php
@@ -4,7 +4,7 @@
extends InvalidArgumentException {
public function __construct($conversion) {
- parent::__construct("Unknown conversion {$conversion}.");
+ parent::__construct(pht('Unknown conversion %s.', $conversion));
}
}
diff --git a/src/xsprintf/jsprintf.php b/src/xsprintf/jsprintf.php
--- a/src/xsprintf/jsprintf.php
+++ b/src/xsprintf/jsprintf.php
@@ -76,9 +76,12 @@
case 'd':
if ($value > 0x1FFFFFFFFFFFFF) {
throw new RangeException(
- "You are passing an integer to jsprintf() which is so large it can ".
- "not be represented without loss of precision by Javascript's ".
- "native Number class. Use %# instead.");
+ pht(
+ "You are passing an integer to %s which is so large it can ".
+ "not be represented without loss of precision by Javascript's ".
+ "native %s class. Use %%# instead.",
+ 'jsprintf()',
+ 'Number'));
}
break;
}
diff --git a/src/xsprintf/qsprintf.php b/src/xsprintf/qsprintf.php
--- a/src/xsprintf/qsprintf.php
+++ b/src/xsprintf/qsprintf.php
@@ -84,7 +84,7 @@
$prefix = '';
if (!($escaper instanceof PhutilQsprintfInterface)) {
- throw new InvalidArgumentException('Invalid database escaper.');
+ throw new InvalidArgumentException(pht('Invalid database escaper.'));
}
switch ($type) {
@@ -105,7 +105,12 @@
}
break;
default:
- throw new Exception('Unknown conversion, try %=d, %=s, or %=f.');
+ throw new Exception(
+ pht(
+ 'Unknown conversion, try %s, %s, or %s.',
+ '%=d',
+ '%=s',
+ '%=f'));
}
break;
@@ -250,12 +255,12 @@
if (!is_array($value)) {
throw new AphrontParameterQueryException(
$query,
- "Expected array argument for %{$type} conversion.");
+ pht('Expected array argument for %%%s conversion.', $type));
}
if (empty($value)) {
throw new AphrontParameterQueryException(
$query,
- "Array for %{$type} conversion is empty.");
+ pht('Array for %%%s conversion is empty.', $type));
}
foreach ($value as $scalar) {
@@ -277,7 +282,7 @@
if (!is_string($value)) {
throw new AphrontParameterQueryException(
$query,
- "Expected a string for %{$type} conversion.");
+ pht('Expected a string for %%%s conversion.', $type));
}
break;
@@ -288,7 +293,7 @@
if (!is_null($value) && !is_numeric($value)) {
throw new AphrontParameterQueryException(
$query,
- "Expected a numeric scalar or null for %{$type} conversion.");
+ pht('Expected a numeric scalar or null for %%%s conversion.', $type));
}
break;
@@ -303,7 +308,7 @@
if (!is_null($value) && !is_scalar($value)) {
throw new AphrontParameterQueryException(
$query,
- "Expected a scalar or null for %{$type} conversion.");
+ pht('Expected a scalar or null for %%%s conversion.', $type));
}
break;
diff --git a/src/xsprintf/queryfx.php b/src/xsprintf/queryfx.php
--- a/src/xsprintf/queryfx.php
+++ b/src/xsprintf/queryfx.php
@@ -16,7 +16,8 @@
$argv = func_get_args();
$ret = call_user_func_array('queryfx_all', $argv);
if (count($ret) > 1) {
- throw new AphrontCountQueryException('Query returned more than one row.');
+ throw new AphrontCountQueryException(
+ pht('Query returned more than one row.'));
} else if (count($ret)) {
return reset($ret);
}
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Sun, Nov 24, 8:59 PM (16 h, 2 m)
Storage Engine
blob
Storage Format
Encrypted (AES-256-CBC)
Storage Handle
6783935
Default Alt Text
D12606.diff (173 KB)
Attached To
Mode
D12606: `pht` all the things
Attached
Detach File
Event Timeline
Log In to Comment