repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.handle
public function handle() { // Filter global methods if (method_exists($this, 'setup')) { $this->setup(); } // Run input filters $this->filterInput(); // Set up all the whereHas and joins constraints $this->filterRelations(); return $this->query; }
php
public function handle() { // Filter global methods if (method_exists($this, 'setup')) { $this->setup(); } // Run input filters $this->filterInput(); // Set up all the whereHas and joins constraints $this->filterRelations(); return $this->query; }
[ "public", "function", "handle", "(", ")", "{", "// Filter global methods", "if", "(", "method_exists", "(", "$", "this", ",", "'setup'", ")", ")", "{", "$", "this", "->", "setup", "(", ")", ";", "}", "// Run input filters", "$", "this", "->", "filterInput", "(", ")", ";", "// Set up all the whereHas and joins constraints", "$", "this", "->", "filterRelations", "(", ")", ";", "return", "$", "this", "->", "query", ";", "}" ]
Handle all filters. @return QueryBuilder
[ "Handle", "all", "filters", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L136-L149
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.related
public function related($relation, $column, $operator = null, $value = null, $boolean = 'and') { if ($column instanceof \Closure) { return $this->addRelated($relation, $column); } // If there is no value it is a where = ? query and we set the appropriate params if ($value === null) { $value = $operator; $operator = '='; } return $this->addRelated($relation, function ($query) use ($column, $operator, $value, $boolean) { return $query->where($column, $operator, $value, $boolean); }); }
php
public function related($relation, $column, $operator = null, $value = null, $boolean = 'and') { if ($column instanceof \Closure) { return $this->addRelated($relation, $column); } // If there is no value it is a where = ? query and we set the appropriate params if ($value === null) { $value = $operator; $operator = '='; } return $this->addRelated($relation, function ($query) use ($column, $operator, $value, $boolean) { return $query->where($column, $operator, $value, $boolean); }); }
[ "public", "function", "related", "(", "$", "relation", ",", "$", "column", ",", "$", "operator", "=", "null", ",", "$", "value", "=", "null", ",", "$", "boolean", "=", "'and'", ")", "{", "if", "(", "$", "column", "instanceof", "\\", "Closure", ")", "{", "return", "$", "this", "->", "addRelated", "(", "$", "relation", ",", "$", "column", ")", ";", "}", "// If there is no value it is a where = ? query and we set the appropriate params", "if", "(", "$", "value", "===", "null", ")", "{", "$", "value", "=", "$", "operator", ";", "$", "operator", "=", "'='", ";", "}", "return", "$", "this", "->", "addRelated", "(", "$", "relation", ",", "function", "(", "$", "query", ")", "use", "(", "$", "column", ",", "$", "operator", ",", "$", "value", ",", "$", "boolean", ")", "{", "return", "$", "query", "->", "where", "(", "$", "column", ",", "$", "operator", ",", "$", "value", ",", "$", "boolean", ")", ";", "}", ")", ";", "}" ]
Add a where constraint to a relationship. @param $relation @param $column @param null $operator @param null $value @param string $boolean @return $this
[ "Add", "a", "where", "constraint", "to", "a", "relationship", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L175-L190
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.filterInput
public function filterInput() { foreach ($this->input as $key => $val) { // Call all local methods on filter $method = $this->getFilterMethod($key); if ($this->methodIsCallable($method)) { $this->{$method}($val); } } }
php
public function filterInput() { foreach ($this->input as $key => $val) { // Call all local methods on filter $method = $this->getFilterMethod($key); if ($this->methodIsCallable($method)) { $this->{$method}($val); } } }
[ "public", "function", "filterInput", "(", ")", "{", "foreach", "(", "$", "this", "->", "input", "as", "$", "key", "=>", "$", "val", ")", "{", "// Call all local methods on filter", "$", "method", "=", "$", "this", "->", "getFilterMethod", "(", "$", "key", ")", ";", "if", "(", "$", "this", "->", "methodIsCallable", "(", "$", "method", ")", ")", "{", "$", "this", "->", "{", "$", "method", "}", "(", "$", "val", ")", ";", "}", "}", "}" ]
Filter with input array.
[ "Filter", "with", "input", "array", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L208-L218
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.getAllRelations
public function getAllRelations() { if (count($this->allRelations) === 0) { $allRelations = array_merge(array_keys($this->relations), array_keys($this->localRelatedFilters)); foreach ($allRelations as $related) { $this->allRelations[$related] = array_merge($this->getLocalRelation($related), $this->getRelatedFilterInput($related)); } } return $this->allRelations; }
php
public function getAllRelations() { if (count($this->allRelations) === 0) { $allRelations = array_merge(array_keys($this->relations), array_keys($this->localRelatedFilters)); foreach ($allRelations as $related) { $this->allRelations[$related] = array_merge($this->getLocalRelation($related), $this->getRelatedFilterInput($related)); } } return $this->allRelations; }
[ "public", "function", "getAllRelations", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "allRelations", ")", "===", "0", ")", "{", "$", "allRelations", "=", "array_merge", "(", "array_keys", "(", "$", "this", "->", "relations", ")", ",", "array_keys", "(", "$", "this", "->", "localRelatedFilters", ")", ")", ";", "foreach", "(", "$", "allRelations", "as", "$", "related", ")", "{", "$", "this", "->", "allRelations", "[", "$", "related", "]", "=", "array_merge", "(", "$", "this", "->", "getLocalRelation", "(", "$", "related", ")", ",", "$", "this", "->", "getRelatedFilterInput", "(", "$", "related", ")", ")", ";", "}", "}", "return", "$", "this", "->", "allRelations", ";", "}" ]
Returns all local relations and relations requiring other Model's Filter's. @return array
[ "Returns", "all", "local", "relations", "and", "relations", "requiring", "other", "Model", "s", "Filter", "s", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L248-L259
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.filterJoinedRelation
public function filterJoinedRelation($related) { // Apply any relation based scope to avoid method duplication $this->callRelatedLocalSetup($related, $this->query); foreach ($this->getLocalRelation($related) as $closure) { // If a relation is defined locally in a method AND is joined // Then we call those defined relation closures on this query $closure($this->query); } // Check if we have input we need to pass through a related Model's filter // Then filter by that related model's filter if (count($relatedFilterInput = $this->getRelatedFilterInput($related)) > 0) { $filterClass = $this->getRelatedFilter($related); // Disable querying joined relations on filters of joined tables. (new $filterClass($this->query, $relatedFilterInput, false))->handle(); } }
php
public function filterJoinedRelation($related) { // Apply any relation based scope to avoid method duplication $this->callRelatedLocalSetup($related, $this->query); foreach ($this->getLocalRelation($related) as $closure) { // If a relation is defined locally in a method AND is joined // Then we call those defined relation closures on this query $closure($this->query); } // Check if we have input we need to pass through a related Model's filter // Then filter by that related model's filter if (count($relatedFilterInput = $this->getRelatedFilterInput($related)) > 0) { $filterClass = $this->getRelatedFilter($related); // Disable querying joined relations on filters of joined tables. (new $filterClass($this->query, $relatedFilterInput, false))->handle(); } }
[ "public", "function", "filterJoinedRelation", "(", "$", "related", ")", "{", "// Apply any relation based scope to avoid method duplication", "$", "this", "->", "callRelatedLocalSetup", "(", "$", "related", ",", "$", "this", "->", "query", ")", ";", "foreach", "(", "$", "this", "->", "getLocalRelation", "(", "$", "related", ")", "as", "$", "closure", ")", "{", "// If a relation is defined locally in a method AND is joined", "// Then we call those defined relation closures on this query", "$", "closure", "(", "$", "this", "->", "query", ")", ";", "}", "// Check if we have input we need to pass through a related Model's filter", "// Then filter by that related model's filter", "if", "(", "count", "(", "$", "relatedFilterInput", "=", "$", "this", "->", "getRelatedFilterInput", "(", "$", "related", ")", ")", ">", "0", ")", "{", "$", "filterClass", "=", "$", "this", "->", "getRelatedFilter", "(", "$", "related", ")", ";", "// Disable querying joined relations on filters of joined tables.", "(", "new", "$", "filterClass", "(", "$", "this", "->", "query", ",", "$", "relatedFilterInput", ",", "false", ")", ")", "->", "handle", "(", ")", ";", "}", "}" ]
Run the filter on models that already have their tables joined. @param $related
[ "Run", "the", "filter", "on", "models", "that", "already", "have", "their", "tables", "joined", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L284-L303
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.getJoinedTables
public function getJoinedTables() { $joins = []; if (is_array($queryJoins = $this->query->getQuery()->joins)) { $joins = array_map(function ($join) { return $join->table; }, $queryJoins); } return $joins; }
php
public function getJoinedTables() { $joins = []; if (is_array($queryJoins = $this->query->getQuery()->joins)) { $joins = array_map(function ($join) { return $join->table; }, $queryJoins); } return $joins; }
[ "public", "function", "getJoinedTables", "(", ")", "{", "$", "joins", "=", "[", "]", ";", "if", "(", "is_array", "(", "$", "queryJoins", "=", "$", "this", "->", "query", "->", "getQuery", "(", ")", "->", "joins", ")", ")", "{", "$", "joins", "=", "array_map", "(", "function", "(", "$", "join", ")", "{", "return", "$", "join", "->", "table", ";", "}", ",", "$", "queryJoins", ")", ";", "}", "return", "$", "joins", ";", "}" ]
Gets all the joined tables. @return array
[ "Gets", "all", "the", "joined", "tables", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L310-L321
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.relationIsJoined
public function relationIsJoined($relation) { if ($this->_joinedTables === null) { $this->_joinedTables = $this->getJoinedTables(); } return in_array($this->getRelatedTable($relation), $this->_joinedTables, true); }
php
public function relationIsJoined($relation) { if ($this->_joinedTables === null) { $this->_joinedTables = $this->getJoinedTables(); } return in_array($this->getRelatedTable($relation), $this->_joinedTables, true); }
[ "public", "function", "relationIsJoined", "(", "$", "relation", ")", "{", "if", "(", "$", "this", "->", "_joinedTables", "===", "null", ")", "{", "$", "this", "->", "_joinedTables", "=", "$", "this", "->", "getJoinedTables", "(", ")", ";", "}", "return", "in_array", "(", "$", "this", "->", "getRelatedTable", "(", "$", "relation", ")", ",", "$", "this", "->", "_joinedTables", ",", "true", ")", ";", "}" ]
Checks if the relation to filter's table is already joined. @param $relation @return bool
[ "Checks", "if", "the", "relation", "to", "filter", "s", "table", "is", "already", "joined", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L329-L336
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.filterUnjoinedRelation
public function filterUnjoinedRelation($related) { $this->query->whereHas($related, function ($q) use ($related) { $this->callRelatedLocalSetup($related, $q); // If we defined it locally then we're running the closure on the related model here right. foreach ($this->getLocalRelation($related) as $closure) { // Run in context of the related model locally $closure($q); } if (count($filterableRelated = $this->getRelatedFilterInput($related)) > 0) { $q->filter($filterableRelated); } return $q; }); }
php
public function filterUnjoinedRelation($related) { $this->query->whereHas($related, function ($q) use ($related) { $this->callRelatedLocalSetup($related, $q); // If we defined it locally then we're running the closure on the related model here right. foreach ($this->getLocalRelation($related) as $closure) { // Run in context of the related model locally $closure($q); } if (count($filterableRelated = $this->getRelatedFilterInput($related)) > 0) { $q->filter($filterableRelated); } return $q; }); }
[ "public", "function", "filterUnjoinedRelation", "(", "$", "related", ")", "{", "$", "this", "->", "query", "->", "whereHas", "(", "$", "related", ",", "function", "(", "$", "q", ")", "use", "(", "$", "related", ")", "{", "$", "this", "->", "callRelatedLocalSetup", "(", "$", "related", ",", "$", "q", ")", ";", "// If we defined it locally then we're running the closure on the related model here right.", "foreach", "(", "$", "this", "->", "getLocalRelation", "(", "$", "related", ")", "as", "$", "closure", ")", "{", "// Run in context of the related model locally", "$", "closure", "(", "$", "q", ")", ";", "}", "if", "(", "count", "(", "$", "filterableRelated", "=", "$", "this", "->", "getRelatedFilterInput", "(", "$", "related", ")", ")", ">", "0", ")", "{", "$", "q", "->", "filter", "(", "$", "filterableRelated", ")", ";", "}", "return", "$", "q", ";", "}", ")", ";", "}" ]
Filters by a relationship that isn't joined by using that relation's ModelFilter. @param $related
[ "Filters", "by", "a", "relationship", "that", "isn", "t", "joined", "by", "using", "that", "relation", "s", "ModelFilter", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L376-L393
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.getRelatedFilterInput
public function getRelatedFilterInput($related) { return array_key_exists($related, $this->relations) ? array_only($this->input, $this->relations[$related]) : []; }
php
public function getRelatedFilterInput($related) { return array_key_exists($related, $this->relations) ? array_only($this->input, $this->relations[$related]) : []; }
[ "public", "function", "getRelatedFilterInput", "(", "$", "related", ")", "{", "return", "array_key_exists", "(", "$", "related", ",", "$", "this", "->", "relations", ")", "?", "array_only", "(", "$", "this", "->", "input", ",", "$", "this", "->", "relations", "[", "$", "related", "]", ")", ":", "[", "]", ";", "}" ]
Get input to pass to a related Model's Filter. @param $related @return array
[ "Get", "input", "to", "pass", "to", "a", "related", "Model", "s", "Filter", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L401-L404
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.input
public function input($key = null, $default = null) { if ($key === null) { return $this->input; } return array_key_exists($key, $this->input) ? $this->input[$key] : $default; }
php
public function input($key = null, $default = null) { if ($key === null) { return $this->input; } return array_key_exists($key, $this->input) ? $this->input[$key] : $default; }
[ "public", "function", "input", "(", "$", "key", "=", "null", ",", "$", "default", "=", "null", ")", "{", "if", "(", "$", "key", "===", "null", ")", "{", "return", "$", "this", "->", "input", ";", "}", "return", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "input", ")", "?", "$", "this", "->", "input", "[", "$", "key", "]", ":", "$", "default", ";", "}" ]
Retrieve input by key or all input as array. @param null $key @param null $default @return array|mixed|null
[ "Retrieve", "input", "by", "key", "or", "all", "input", "as", "array", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L455-L462
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.dropIdSuffix
public function dropIdSuffix($bool = null) { if ($bool === null) { return $this->drop_id; } return $this->drop_id = $bool; }
php
public function dropIdSuffix($bool = null) { if ($bool === null) { return $this->drop_id; } return $this->drop_id = $bool; }
[ "public", "function", "dropIdSuffix", "(", "$", "bool", "=", "null", ")", "{", "if", "(", "$", "bool", "===", "null", ")", "{", "return", "$", "this", "->", "drop_id", ";", "}", "return", "$", "this", "->", "drop_id", "=", "$", "bool", ";", "}" ]
Set to drop `_id` from input. Mainly for testing. @param null $bool @return bool
[ "Set", "to", "drop", "_id", "from", "input", ".", "Mainly", "for", "testing", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L521-L528
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.convertToCamelCasedMethods
public function convertToCamelCasedMethods($bool = null) { if ($bool === null) { return $this->camel_cased_methods; } return $this->camel_cased_methods = $bool; }
php
public function convertToCamelCasedMethods($bool = null) { if ($bool === null) { return $this->camel_cased_methods; } return $this->camel_cased_methods = $bool; }
[ "public", "function", "convertToCamelCasedMethods", "(", "$", "bool", "=", "null", ")", "{", "if", "(", "$", "bool", "===", "null", ")", "{", "return", "$", "this", "->", "camel_cased_methods", ";", "}", "return", "$", "this", "->", "camel_cased_methods", "=", "$", "bool", ";", "}" ]
Convert input to camel_case. Mainly for testing. @param null $bool @return bool
[ "Convert", "input", "to", "camel_case", ".", "Mainly", "for", "testing", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L537-L544
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.whitelistMethod
public function whitelistMethod($method) { $this->blacklist = array_filter($this->blacklist, function ($name) use ($method) { return $name !== $method; }); return $this; }
php
public function whitelistMethod($method) { $this->blacklist = array_filter($this->blacklist, function ($name) use ($method) { return $name !== $method; }); return $this; }
[ "public", "function", "whitelistMethod", "(", "$", "method", ")", "{", "$", "this", "->", "blacklist", "=", "array_filter", "(", "$", "this", "->", "blacklist", ",", "function", "(", "$", "name", ")", "use", "(", "$", "method", ")", "{", "return", "$", "name", "!==", "$", "method", ";", "}", ")", ";", "return", "$", "this", ";", "}" ]
Remove a method from the blacklist. @param string $method @return $this
[ "Remove", "a", "method", "from", "the", "blacklist", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L563-L570
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.methodIsCallable
public function methodIsCallable($method) { return ! $this->methodIsBlacklisted($method) && method_exists($this, $method) && ! method_exists(ModelFilter::class, $method); }
php
public function methodIsCallable($method) { return ! $this->methodIsBlacklisted($method) && method_exists($this, $method) && ! method_exists(ModelFilter::class, $method); }
[ "public", "function", "methodIsCallable", "(", "$", "method", ")", "{", "return", "!", "$", "this", "->", "methodIsBlacklisted", "(", "$", "method", ")", "&&", "method_exists", "(", "$", "this", ",", "$", "method", ")", "&&", "!", "method_exists", "(", "ModelFilter", "::", "class", ",", "$", "method", ")", ";", "}" ]
Check if the method is not blacklisted and callable on the extended class. @param $method @return bool
[ "Check", "if", "the", "method", "is", "not", "blacklisted", "and", "callable", "on", "the", "extended", "class", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L586-L591
train
Tucker-Eric/EloquentFilter
src/ModelFilter.php
ModelFilter.registerMacros
private function registerMacros() { if ( method_exists(Relation::class, 'hasMacro') && method_exists(Relation::class, 'macro') && ! Relation::hasMacro('paginateFilter') && ! Relation::hasMacro('simplePaginateFilter') ) { Relation::macro('paginateFilter', function () { $paginator = call_user_func_array([$this, 'paginate'], func_get_args()); $paginator->appends($this->getRelated()->filtered); return $paginator; }); Relation::macro('simplePaginateFilter', function () { $paginator = call_user_func_array([$this, 'simplePaginate'], func_get_args()); $paginator->appends($this->getRelated()->filtered); return $paginator; }); } }
php
private function registerMacros() { if ( method_exists(Relation::class, 'hasMacro') && method_exists(Relation::class, 'macro') && ! Relation::hasMacro('paginateFilter') && ! Relation::hasMacro('simplePaginateFilter') ) { Relation::macro('paginateFilter', function () { $paginator = call_user_func_array([$this, 'paginate'], func_get_args()); $paginator->appends($this->getRelated()->filtered); return $paginator; }); Relation::macro('simplePaginateFilter', function () { $paginator = call_user_func_array([$this, 'simplePaginate'], func_get_args()); $paginator->appends($this->getRelated()->filtered); return $paginator; }); } }
[ "private", "function", "registerMacros", "(", ")", "{", "if", "(", "method_exists", "(", "Relation", "::", "class", ",", "'hasMacro'", ")", "&&", "method_exists", "(", "Relation", "::", "class", ",", "'macro'", ")", "&&", "!", "Relation", "::", "hasMacro", "(", "'paginateFilter'", ")", "&&", "!", "Relation", "::", "hasMacro", "(", "'simplePaginateFilter'", ")", ")", "{", "Relation", "::", "macro", "(", "'paginateFilter'", ",", "function", "(", ")", "{", "$", "paginator", "=", "call_user_func_array", "(", "[", "$", "this", ",", "'paginate'", "]", ",", "func_get_args", "(", ")", ")", ";", "$", "paginator", "->", "appends", "(", "$", "this", "->", "getRelated", "(", ")", "->", "filtered", ")", ";", "return", "$", "paginator", ";", "}", ")", ";", "Relation", "::", "macro", "(", "'simplePaginateFilter'", ",", "function", "(", ")", "{", "$", "paginator", "=", "call_user_func_array", "(", "[", "$", "this", ",", "'simplePaginate'", "]", ",", "func_get_args", "(", ")", ")", ";", "$", "paginator", "->", "appends", "(", "$", "this", "->", "getRelated", "(", ")", "->", "filtered", ")", ";", "return", "$", "paginator", ";", "}", ")", ";", "}", "}" ]
Register paginate and simplePaginate macros on relations BelongsToMany overrides the QueryBuilder's paginate to append the pivot.
[ "Register", "paginate", "and", "simplePaginate", "macros", "on", "relations", "BelongsToMany", "overrides", "the", "QueryBuilder", "s", "paginate", "to", "append", "the", "pivot", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/ModelFilter.php#L597-L618
train
Tucker-Eric/EloquentFilter
src/Filterable.php
Filterable.scopeFilter
public function scopeFilter($query, array $input = [], $filter = null) { // Resolve the current Model's filter if ($filter === null) { $filter = $this->getModelFilterClass(); } // Create the model filter instance $modelFilter = new $filter($query, $input); // Set the input that was used in the filter (this will exclude empty strings) $this->filtered = $modelFilter->input(); // Return the filter query return $modelFilter->handle(); }
php
public function scopeFilter($query, array $input = [], $filter = null) { // Resolve the current Model's filter if ($filter === null) { $filter = $this->getModelFilterClass(); } // Create the model filter instance $modelFilter = new $filter($query, $input); // Set the input that was used in the filter (this will exclude empty strings) $this->filtered = $modelFilter->input(); // Return the filter query return $modelFilter->handle(); }
[ "public", "function", "scopeFilter", "(", "$", "query", ",", "array", "$", "input", "=", "[", "]", ",", "$", "filter", "=", "null", ")", "{", "// Resolve the current Model's filter", "if", "(", "$", "filter", "===", "null", ")", "{", "$", "filter", "=", "$", "this", "->", "getModelFilterClass", "(", ")", ";", "}", "// Create the model filter instance", "$", "modelFilter", "=", "new", "$", "filter", "(", "$", "query", ",", "$", "input", ")", ";", "// Set the input that was used in the filter (this will exclude empty strings)", "$", "this", "->", "filtered", "=", "$", "modelFilter", "->", "input", "(", ")", ";", "// Return the filter query", "return", "$", "modelFilter", "->", "handle", "(", ")", ";", "}" ]
Creates local scope to run the filter. @param $query @param array $input @param null|string|ModelFilter $filter @return \Illuminate\Database\Eloquent\Builder
[ "Creates", "local", "scope", "to", "run", "the", "filter", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/Filterable.php#L22-L37
train
Tucker-Eric/EloquentFilter
src/Filterable.php
Filterable.provideFilter
public function provideFilter($filter = null) { if ($filter === null) { $filter = config('eloquentfilter.namespace', 'App\\ModelFilters\\').class_basename($this).'Filter'; } return $filter; }
php
public function provideFilter($filter = null) { if ($filter === null) { $filter = config('eloquentfilter.namespace', 'App\\ModelFilters\\').class_basename($this).'Filter'; } return $filter; }
[ "public", "function", "provideFilter", "(", "$", "filter", "=", "null", ")", "{", "if", "(", "$", "filter", "===", "null", ")", "{", "$", "filter", "=", "config", "(", "'eloquentfilter.namespace'", ",", "'App\\\\ModelFilters\\\\'", ")", ".", "class_basename", "(", "$", "this", ")", ".", "'Filter'", ";", "}", "return", "$", "filter", ";", "}" ]
Returns ModelFilter class to be instantiated. @param null|string $filter @return string
[ "Returns", "ModelFilter", "class", "to", "be", "instantiated", "." ]
85edfce2e0497f8570d9a8d36a3ad32eb261216f
https://github.com/Tucker-Eric/EloquentFilter/blob/85edfce2e0497f8570d9a8d36a3ad32eb261216f/src/Filterable.php#L85-L92
train
stefanzweifel/laravel-stats
src/Statistics/ProjectStatistics.php
ProjectStatistics.total
public function total() : array { $stats = $this->generate(); return [ 'Total', $stats->sum('number_of_classes'), $stats->sum('methods'), round($stats->avg('methods_per_class'), 2), $stats->sum('lines'), $stats->sum('loc'), round($stats->avg('loc_per_method'), 2), ]; }
php
public function total() : array { $stats = $this->generate(); return [ 'Total', $stats->sum('number_of_classes'), $stats->sum('methods'), round($stats->avg('methods_per_class'), 2), $stats->sum('lines'), $stats->sum('loc'), round($stats->avg('loc_per_method'), 2), ]; }
[ "public", "function", "total", "(", ")", ":", "array", "{", "$", "stats", "=", "$", "this", "->", "generate", "(", ")", ";", "return", "[", "'Total'", ",", "$", "stats", "->", "sum", "(", "'number_of_classes'", ")", ",", "$", "stats", "->", "sum", "(", "'methods'", ")", ",", "round", "(", "$", "stats", "->", "avg", "(", "'methods_per_class'", ")", ",", "2", ")", ",", "$", "stats", "->", "sum", "(", "'lines'", ")", ",", "$", "stats", "->", "sum", "(", "'loc'", ")", ",", "round", "(", "$", "stats", "->", "avg", "(", "'loc_per_method'", ")", ",", "2", ")", ",", "]", ";", "}" ]
Create Total Row for current Project Statistics. @return array
[ "Create", "Total", "Row", "for", "current", "Project", "Statistics", "." ]
e7bb5b6a376e840167ec26d10754c4c1e0fdf12a
https://github.com/stefanzweifel/laravel-stats/blob/e7bb5b6a376e840167ec26d10754c4c1e0fdf12a/src/Statistics/ProjectStatistics.php#L61-L74
train
stefanzweifel/laravel-stats
src/Statistics/ProjectStatistics.php
ProjectStatistics.generate
private function generate() : Collection { if (! $this->cache) { $this->cache = $this->components ->map(function ($classes, $name) { return (new ComponentStatistics($name, $classes))->toArray(); }) ->sortBy(function ($component, $_) { return Str::contains($component['component'], 'Test') ? 1 : $component['component']; }); } return $this->cache; }
php
private function generate() : Collection { if (! $this->cache) { $this->cache = $this->components ->map(function ($classes, $name) { return (new ComponentStatistics($name, $classes))->toArray(); }) ->sortBy(function ($component, $_) { return Str::contains($component['component'], 'Test') ? 1 : $component['component']; }); } return $this->cache; }
[ "private", "function", "generate", "(", ")", ":", "Collection", "{", "if", "(", "!", "$", "this", "->", "cache", ")", "{", "$", "this", "->", "cache", "=", "$", "this", "->", "components", "->", "map", "(", "function", "(", "$", "classes", ",", "$", "name", ")", "{", "return", "(", "new", "ComponentStatistics", "(", "$", "name", ",", "$", "classes", ")", ")", "->", "toArray", "(", ")", ";", "}", ")", "->", "sortBy", "(", "function", "(", "$", "component", ",", "$", "_", ")", "{", "return", "Str", "::", "contains", "(", "$", "component", "[", "'component'", "]", ",", "'Test'", ")", "?", "1", ":", "$", "component", "[", "'component'", "]", ";", "}", ")", ";", "}", "return", "$", "this", "->", "cache", ";", "}" ]
Generate Project Statistics. @return Collection
[ "Generate", "Project", "Statistics", "." ]
e7bb5b6a376e840167ec26d10754c4c1e0fdf12a
https://github.com/stefanzweifel/laravel-stats/blob/e7bb5b6a376e840167ec26d10754c4c1e0fdf12a/src/Statistics/ProjectStatistics.php#L81-L94
train
stefanzweifel/laravel-stats
src/Statistics/ComponentStatistics.php
ComponentStatistics.getLines
public function getLines() : int { return $this->classes ->map(function ($class) { return $class->getFileName(); }) ->pipe(function ($classes) { return app(Analyser::class)->countFiles($classes->all(), false)['loc']; }); }
php
public function getLines() : int { return $this->classes ->map(function ($class) { return $class->getFileName(); }) ->pipe(function ($classes) { return app(Analyser::class)->countFiles($classes->all(), false)['loc']; }); }
[ "public", "function", "getLines", "(", ")", ":", "int", "{", "return", "$", "this", "->", "classes", "->", "map", "(", "function", "(", "$", "class", ")", "{", "return", "$", "class", "->", "getFileName", "(", ")", ";", "}", ")", "->", "pipe", "(", "function", "(", "$", "classes", ")", "{", "return", "app", "(", "Analyser", "::", "class", ")", "->", "countFiles", "(", "$", "classes", "->", "all", "(", ")", ",", "false", ")", "[", "'loc'", "]", ";", "}", ")", ";", "}" ]
Return the total number of lines. @return int
[ "Return", "the", "total", "number", "of", "lines", "." ]
e7bb5b6a376e840167ec26d10754c4c1e0fdf12a
https://github.com/stefanzweifel/laravel-stats/blob/e7bb5b6a376e840167ec26d10754c4c1e0fdf12a/src/Statistics/ComponentStatistics.php#L80-L89
train
stefanzweifel/laravel-stats
src/Statistics/ComponentStatistics.php
ComponentStatistics.getLinesOfCode
public function getLinesOfCode() : float { return $this->classes ->map(function ($class) { return $class->getFileName(); }) ->pipe(function ($classes) { return app(Analyser::class)->countFiles($classes->all(), false)['lloc']; }); }
php
public function getLinesOfCode() : float { return $this->classes ->map(function ($class) { return $class->getFileName(); }) ->pipe(function ($classes) { return app(Analyser::class)->countFiles($classes->all(), false)['lloc']; }); }
[ "public", "function", "getLinesOfCode", "(", ")", ":", "float", "{", "return", "$", "this", "->", "classes", "->", "map", "(", "function", "(", "$", "class", ")", "{", "return", "$", "class", "->", "getFileName", "(", ")", ";", "}", ")", "->", "pipe", "(", "function", "(", "$", "classes", ")", "{", "return", "app", "(", "Analyser", "::", "class", ")", "->", "countFiles", "(", "$", "classes", "->", "all", "(", ")", ",", "false", ")", "[", "'lloc'", "]", ";", "}", ")", ";", "}" ]
Return the total number of lines of code. @return float
[ "Return", "the", "total", "number", "of", "lines", "of", "code", "." ]
e7bb5b6a376e840167ec26d10754c4c1e0fdf12a
https://github.com/stefanzweifel/laravel-stats/blob/e7bb5b6a376e840167ec26d10754c4c1e0fdf12a/src/Statistics/ComponentStatistics.php#L96-L105
train
stefanzweifel/laravel-stats
src/Statistics/ComponentStatistics.php
ComponentStatistics.toArray
public function toArray() : array { return [ 'component' => $this->name, 'number_of_classes' => $this->getNumberOfClasses(), 'methods' => $this->getNumberOfMethods(), 'methods_per_class' => $this->getNumberOfMethodsPerClass(), 'lines' => $this->getLines(), 'loc' => $this->getLinesOfCode(), 'loc_per_method' => $this->getLinesOfCodePerMethod(), ]; }
php
public function toArray() : array { return [ 'component' => $this->name, 'number_of_classes' => $this->getNumberOfClasses(), 'methods' => $this->getNumberOfMethods(), 'methods_per_class' => $this->getNumberOfMethodsPerClass(), 'lines' => $this->getLines(), 'loc' => $this->getLinesOfCode(), 'loc_per_method' => $this->getLinesOfCodePerMethod(), ]; }
[ "public", "function", "toArray", "(", ")", ":", "array", "{", "return", "[", "'component'", "=>", "$", "this", "->", "name", ",", "'number_of_classes'", "=>", "$", "this", "->", "getNumberOfClasses", "(", ")", ",", "'methods'", "=>", "$", "this", "->", "getNumberOfMethods", "(", ")", ",", "'methods_per_class'", "=>", "$", "this", "->", "getNumberOfMethodsPerClass", "(", ")", ",", "'lines'", "=>", "$", "this", "->", "getLines", "(", ")", ",", "'loc'", "=>", "$", "this", "->", "getLinesOfCode", "(", ")", ",", "'loc_per_method'", "=>", "$", "this", "->", "getLinesOfCodePerMethod", "(", ")", ",", "]", ";", "}" ]
Generate Statistics Array for the given Component. @return array
[ "Generate", "Statistics", "Array", "for", "the", "given", "Component", "." ]
e7bb5b6a376e840167ec26d10754c4c1e0fdf12a
https://github.com/stefanzweifel/laravel-stats/blob/e7bb5b6a376e840167ec26d10754c4c1e0fdf12a/src/Statistics/ComponentStatistics.php#L126-L137
train
stefanzweifel/laravel-stats
src/ComponentFinder.php
ComponentFinder.get
public function get() { return $this->findAndLoadClasses() ->map(function ($class) { return new ReflectionClass($class); }) ->reject(function ($class) { return $this->rejectionStrategy->shouldClassBeRejected($class); }) ->reject(function ($class) { foreach (config('stats.ignored_namespaces', []) as $namespace) { if (Str::startsWith($class->getNamespaceName(), $namespace)) { return true; } } return false; }) ->groupBy(function ($class) { return (new Classifier)->classify($class); }); }
php
public function get() { return $this->findAndLoadClasses() ->map(function ($class) { return new ReflectionClass($class); }) ->reject(function ($class) { return $this->rejectionStrategy->shouldClassBeRejected($class); }) ->reject(function ($class) { foreach (config('stats.ignored_namespaces', []) as $namespace) { if (Str::startsWith($class->getNamespaceName(), $namespace)) { return true; } } return false; }) ->groupBy(function ($class) { return (new Classifier)->classify($class); }); }
[ "public", "function", "get", "(", ")", "{", "return", "$", "this", "->", "findAndLoadClasses", "(", ")", "->", "map", "(", "function", "(", "$", "class", ")", "{", "return", "new", "ReflectionClass", "(", "$", "class", ")", ";", "}", ")", "->", "reject", "(", "function", "(", "$", "class", ")", "{", "return", "$", "this", "->", "rejectionStrategy", "->", "shouldClassBeRejected", "(", "$", "class", ")", ";", "}", ")", "->", "reject", "(", "function", "(", "$", "class", ")", "{", "foreach", "(", "config", "(", "'stats.ignored_namespaces'", ",", "[", "]", ")", "as", "$", "namespace", ")", "{", "if", "(", "Str", "::", "startsWith", "(", "$", "class", "->", "getNamespaceName", "(", ")", ",", "$", "namespace", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", ")", "->", "groupBy", "(", "function", "(", "$", "class", ")", "{", "return", "(", "new", "Classifier", ")", "->", "classify", "(", "$", "class", ")", ";", "}", ")", ";", "}" ]
Scan the Project for PHP Classes, turn them into ReflectionClasses, reject unwanted Classes and sort them into Components. @return Collection
[ "Scan", "the", "Project", "for", "PHP", "Classes", "turn", "them", "into", "ReflectionClasses", "reject", "unwanted", "Classes", "and", "sort", "them", "into", "Components", "." ]
e7bb5b6a376e840167ec26d10754c4c1e0fdf12a
https://github.com/stefanzweifel/laravel-stats/blob/e7bb5b6a376e840167ec26d10754c4c1e0fdf12a/src/ComponentFinder.php#L32-L53
train
stefanzweifel/laravel-stats
src/ComponentFinder.php
ComponentFinder.findFilesInProjectPath
protected function findFilesInProjectPath() : Collection { $excludes = collect(config('stats.exclude', [])); $files = (new Finder)->files() ->in(config('stats.paths', [])) ->name('*.php'); return collect($files) ->reject(function ($file) use ($excludes) { return $this->isExcluded($file, $excludes); }); }
php
protected function findFilesInProjectPath() : Collection { $excludes = collect(config('stats.exclude', [])); $files = (new Finder)->files() ->in(config('stats.paths', [])) ->name('*.php'); return collect($files) ->reject(function ($file) use ($excludes) { return $this->isExcluded($file, $excludes); }); }
[ "protected", "function", "findFilesInProjectPath", "(", ")", ":", "Collection", "{", "$", "excludes", "=", "collect", "(", "config", "(", "'stats.exclude'", ",", "[", "]", ")", ")", ";", "$", "files", "=", "(", "new", "Finder", ")", "->", "files", "(", ")", "->", "in", "(", "config", "(", "'stats.paths'", ",", "[", "]", ")", ")", "->", "name", "(", "'*.php'", ")", ";", "return", "collect", "(", "$", "files", ")", "->", "reject", "(", "function", "(", "$", "file", ")", "use", "(", "$", "excludes", ")", "{", "return", "$", "this", "->", "isExcluded", "(", "$", "file", ",", "$", "excludes", ")", ";", "}", ")", ";", "}" ]
Find PHP Files which should be analyzed. @return Collection
[ "Find", "PHP", "Files", "which", "should", "be", "analyzed", "." ]
e7bb5b6a376e840167ec26d10754c4c1e0fdf12a
https://github.com/stefanzweifel/laravel-stats/blob/e7bb5b6a376e840167ec26d10754c4c1e0fdf12a/src/ComponentFinder.php#L84-L96
train
stefanzweifel/laravel-stats
src/ComponentFinder.php
ComponentFinder.isExcluded
protected function isExcluded(SplFileInfo $file, Collection $excludes) { return $excludes->contains(function ($exclude) use ($file) { return Str::startsWith($file->getPathname(), $exclude); }); }
php
protected function isExcluded(SplFileInfo $file, Collection $excludes) { return $excludes->contains(function ($exclude) use ($file) { return Str::startsWith($file->getPathname(), $exclude); }); }
[ "protected", "function", "isExcluded", "(", "SplFileInfo", "$", "file", ",", "Collection", "$", "excludes", ")", "{", "return", "$", "excludes", "->", "contains", "(", "function", "(", "$", "exclude", ")", "use", "(", "$", "file", ")", "{", "return", "Str", "::", "startsWith", "(", "$", "file", "->", "getPathname", "(", ")", ",", "$", "exclude", ")", ";", "}", ")", ";", "}" ]
Determine if a file has been defined in the exclude configuration. @param SplFileInfo $file @param Collection $excludes @return bool
[ "Determine", "if", "a", "file", "has", "been", "defined", "in", "the", "exclude", "configuration", "." ]
e7bb5b6a376e840167ec26d10754c4c1e0fdf12a
https://github.com/stefanzweifel/laravel-stats/blob/e7bb5b6a376e840167ec26d10754c4c1e0fdf12a/src/ComponentFinder.php#L105-L110
train
stefanzweifel/laravel-stats
src/Classifier.php
Classifier.classify
public function classify(ReflectionClass $class) { $mergedClassifiers = array_merge( self::DEFAULT_CLASSIFIER, config('stats.custom_component_classifier', []) ); foreach ($mergedClassifiers as $classifier) { $c = new $classifier(); if (! $this->implementsContract($classifier)) { throw new Exception("Classifier {$classifier} does not implement ".ClassifierContract::class.'.'); } try { $satisfied = $c->satisfies($class); } catch (Exception $e) { $satisfied = false; } if ($satisfied) { return $c->getName(); } } return 'Other'; }
php
public function classify(ReflectionClass $class) { $mergedClassifiers = array_merge( self::DEFAULT_CLASSIFIER, config('stats.custom_component_classifier', []) ); foreach ($mergedClassifiers as $classifier) { $c = new $classifier(); if (! $this->implementsContract($classifier)) { throw new Exception("Classifier {$classifier} does not implement ".ClassifierContract::class.'.'); } try { $satisfied = $c->satisfies($class); } catch (Exception $e) { $satisfied = false; } if ($satisfied) { return $c->getName(); } } return 'Other'; }
[ "public", "function", "classify", "(", "ReflectionClass", "$", "class", ")", "{", "$", "mergedClassifiers", "=", "array_merge", "(", "self", "::", "DEFAULT_CLASSIFIER", ",", "config", "(", "'stats.custom_component_classifier'", ",", "[", "]", ")", ")", ";", "foreach", "(", "$", "mergedClassifiers", "as", "$", "classifier", ")", "{", "$", "c", "=", "new", "$", "classifier", "(", ")", ";", "if", "(", "!", "$", "this", "->", "implementsContract", "(", "$", "classifier", ")", ")", "{", "throw", "new", "Exception", "(", "\"Classifier {$classifier} does not implement \"", ".", "ClassifierContract", "::", "class", ".", "'.'", ")", ";", "}", "try", "{", "$", "satisfied", "=", "$", "c", "->", "satisfies", "(", "$", "class", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "satisfied", "=", "false", ";", "}", "if", "(", "$", "satisfied", ")", "{", "return", "$", "c", "->", "getName", "(", ")", ";", "}", "}", "return", "'Other'", ";", "}" ]
Classify a given Class by an available Classifier Strategy. @param ReflectionClass $class @return string
[ "Classify", "a", "given", "Class", "by", "an", "available", "Classifier", "Strategy", "." ]
e7bb5b6a376e840167ec26d10754c4c1e0fdf12a
https://github.com/stefanzweifel/laravel-stats/blob/e7bb5b6a376e840167ec26d10754c4c1e0fdf12a/src/Classifier.php#L67-L93
train
stefanzweifel/laravel-stats
src/ReflectionClass.php
ReflectionClass.getDefinedMethods
public function getDefinedMethods() : Collection { return collect($this->getMethods()) ->filter(function ($method) { return $method->getFileName() == $this->getFileName(); }); }
php
public function getDefinedMethods() : Collection { return collect($this->getMethods()) ->filter(function ($method) { return $method->getFileName() == $this->getFileName(); }); }
[ "public", "function", "getDefinedMethods", "(", ")", ":", "Collection", "{", "return", "collect", "(", "$", "this", "->", "getMethods", "(", ")", ")", "->", "filter", "(", "function", "(", "$", "method", ")", "{", "return", "$", "method", "->", "getFileName", "(", ")", "==", "$", "this", "->", "getFileName", "(", ")", ";", "}", ")", ";", "}" ]
Return a collection of methods defined on the given class. This ignores methods defined in parent class, traits etc. @return Collection
[ "Return", "a", "collection", "of", "methods", "defined", "on", "the", "given", "class", ".", "This", "ignores", "methods", "defined", "in", "parent", "class", "traits", "etc", "." ]
e7bb5b6a376e840167ec26d10754c4c1e0fdf12a
https://github.com/stefanzweifel/laravel-stats/blob/e7bb5b6a376e840167ec26d10754c4c1e0fdf12a/src/ReflectionClass.php#L41-L47
train
beyondcode/laravel-vouchers
src/Vouchers.php
Vouchers.generate
public function generate(int $amount = 1): array { $codes = []; for ($i = 1; $i <= $amount; $i++) { $codes[] = $this->getUniqueVoucher(); } return $codes; }
php
public function generate(int $amount = 1): array { $codes = []; for ($i = 1; $i <= $amount; $i++) { $codes[] = $this->getUniqueVoucher(); } return $codes; }
[ "public", "function", "generate", "(", "int", "$", "amount", "=", "1", ")", ":", "array", "{", "$", "codes", "=", "[", "]", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<=", "$", "amount", ";", "$", "i", "++", ")", "{", "$", "codes", "[", "]", "=", "$", "this", "->", "getUniqueVoucher", "(", ")", ";", "}", "return", "$", "codes", ";", "}" ]
Generate the specified amount of codes and return an array with all the generated codes. @param int $amount @return array
[ "Generate", "the", "specified", "amount", "of", "codes", "and", "return", "an", "array", "with", "all", "the", "generated", "codes", "." ]
7b559c86725cf3ddcc27c715314568364f39aa86
https://github.com/beyondcode/laravel-vouchers/blob/7b559c86725cf3ddcc27c715314568364f39aa86/src/Vouchers.php#L27-L36
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.getMetadataForRegion
private function getMetadataForRegion($regionCode) { $countryCallingCode = $this->phoneUtil->getCountryCodeForRegion($regionCode); $mainCountry = $this->phoneUtil->getRegionCodeForCountryCode($countryCallingCode); $metadata = $this->phoneUtil->getMetadataForRegion($mainCountry); if ($metadata !== null) { return $metadata; } // Set to a default instance of teh metadata. This allows us to function with an incorrect // region code, even if the formatting only works for numbers specified with "+". return self::$emptyMetadata; }
php
private function getMetadataForRegion($regionCode) { $countryCallingCode = $this->phoneUtil->getCountryCodeForRegion($regionCode); $mainCountry = $this->phoneUtil->getRegionCodeForCountryCode($countryCallingCode); $metadata = $this->phoneUtil->getMetadataForRegion($mainCountry); if ($metadata !== null) { return $metadata; } // Set to a default instance of teh metadata. This allows us to function with an incorrect // region code, even if the formatting only works for numbers specified with "+". return self::$emptyMetadata; }
[ "private", "function", "getMetadataForRegion", "(", "$", "regionCode", ")", "{", "$", "countryCallingCode", "=", "$", "this", "->", "phoneUtil", "->", "getCountryCodeForRegion", "(", "$", "regionCode", ")", ";", "$", "mainCountry", "=", "$", "this", "->", "phoneUtil", "->", "getRegionCodeForCountryCode", "(", "$", "countryCallingCode", ")", ";", "$", "metadata", "=", "$", "this", "->", "phoneUtil", "->", "getMetadataForRegion", "(", "$", "mainCountry", ")", ";", "if", "(", "$", "metadata", "!==", "null", ")", "{", "return", "$", "metadata", ";", "}", "// Set to a default instance of teh metadata. This allows us to function with an incorrect", "// region code, even if the formatting only works for numbers specified with \"+\".", "return", "self", "::", "$", "emptyMetadata", ";", "}" ]
The metadata needed by this class is the same for all regions sharing the same country calling code. Therefore, we return the metadata for the 'main' region for this country calling code. @param string $regionCode @return PhoneMetadata
[ "The", "metadata", "needed", "by", "this", "class", "is", "the", "same", "for", "all", "regions", "sharing", "the", "same", "country", "calling", "code", ".", "Therefore", "we", "return", "the", "metadata", "for", "the", "main", "region", "for", "this", "country", "calling", "code", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L214-L225
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.maybeCreateNewTemplate
private function maybeCreateNewTemplate() { // When there are multiple available formats, the formatter uses the first format where a // formatting template could be created. foreach ($this->possibleFormats as $key => $numberFormat) { $pattern = $numberFormat->getPattern(); if ($this->currentFormattingPattern == $pattern) { return false; } if ($this->createFormattingTemplate($numberFormat)) { $this->currentFormattingPattern = $pattern; $nationalPrefixSeparatorsMatcher = new Matcher(self::$nationalPrefixSeparatorsPattern, $numberFormat->getNationalPrefixFormattingRule()); $this->shouldAddSpaceAfterNationalPrefix = $nationalPrefixSeparatorsMatcher->find(); // With a new formatting template, the matched position using the old template // needs to be reset. $this->lastMatchPosition = 0; return true; } // Remove the current number format from $this->possibleFormats unset($this->possibleFormats[$key]); } $this->ableToFormat = false; return false; }
php
private function maybeCreateNewTemplate() { // When there are multiple available formats, the formatter uses the first format where a // formatting template could be created. foreach ($this->possibleFormats as $key => $numberFormat) { $pattern = $numberFormat->getPattern(); if ($this->currentFormattingPattern == $pattern) { return false; } if ($this->createFormattingTemplate($numberFormat)) { $this->currentFormattingPattern = $pattern; $nationalPrefixSeparatorsMatcher = new Matcher(self::$nationalPrefixSeparatorsPattern, $numberFormat->getNationalPrefixFormattingRule()); $this->shouldAddSpaceAfterNationalPrefix = $nationalPrefixSeparatorsMatcher->find(); // With a new formatting template, the matched position using the old template // needs to be reset. $this->lastMatchPosition = 0; return true; } // Remove the current number format from $this->possibleFormats unset($this->possibleFormats[$key]); } $this->ableToFormat = false; return false; }
[ "private", "function", "maybeCreateNewTemplate", "(", ")", "{", "// When there are multiple available formats, the formatter uses the first format where a", "// formatting template could be created.", "foreach", "(", "$", "this", "->", "possibleFormats", "as", "$", "key", "=>", "$", "numberFormat", ")", "{", "$", "pattern", "=", "$", "numberFormat", "->", "getPattern", "(", ")", ";", "if", "(", "$", "this", "->", "currentFormattingPattern", "==", "$", "pattern", ")", "{", "return", "false", ";", "}", "if", "(", "$", "this", "->", "createFormattingTemplate", "(", "$", "numberFormat", ")", ")", "{", "$", "this", "->", "currentFormattingPattern", "=", "$", "pattern", ";", "$", "nationalPrefixSeparatorsMatcher", "=", "new", "Matcher", "(", "self", "::", "$", "nationalPrefixSeparatorsPattern", ",", "$", "numberFormat", "->", "getNationalPrefixFormattingRule", "(", ")", ")", ";", "$", "this", "->", "shouldAddSpaceAfterNationalPrefix", "=", "$", "nationalPrefixSeparatorsMatcher", "->", "find", "(", ")", ";", "// With a new formatting template, the matched position using the old template", "// needs to be reset.", "$", "this", "->", "lastMatchPosition", "=", "0", ";", "return", "true", ";", "}", "// Remove the current number format from $this->possibleFormats", "unset", "(", "$", "this", "->", "possibleFormats", "[", "$", "key", "]", ")", ";", "}", "$", "this", "->", "ableToFormat", "=", "false", ";", "return", "false", ";", "}" ]
Returns true if a new template is created as opposed to reusing the existing template. @return bool
[ "Returns", "true", "if", "a", "new", "template", "is", "created", "as", "opposed", "to", "reusing", "the", "existing", "template", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L231-L256
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.getFormattingTemplate
private function getFormattingTemplate($numberPattern, $numberFormat) { // Creates a phone number consisting only of the digit 9 that matches the // numberPattern by applying the pattern to the longestPhoneNumber string. $longestPhoneNumber = '999999999999999'; $m = new Matcher($numberPattern, $longestPhoneNumber); $m->find(); $aPhoneNumber = $m->group(); // No formatting template can be created if the number of digits entered entered so far // is longer than the maximum the current formatting rule can accommodate. if (mb_strlen($aPhoneNumber) < mb_strlen($this->nationalNumber)) { return ''; } // Formats the number according to $numberFormat $template = preg_replace('/' . $numberPattern . '/' . PhoneNumberUtil::REGEX_FLAGS, $numberFormat, $aPhoneNumber); // Replaces each digit with character self::$digitPlattern $template = preg_replace('/9/', self::$digitPattern, $template); return $template; }
php
private function getFormattingTemplate($numberPattern, $numberFormat) { // Creates a phone number consisting only of the digit 9 that matches the // numberPattern by applying the pattern to the longestPhoneNumber string. $longestPhoneNumber = '999999999999999'; $m = new Matcher($numberPattern, $longestPhoneNumber); $m->find(); $aPhoneNumber = $m->group(); // No formatting template can be created if the number of digits entered entered so far // is longer than the maximum the current formatting rule can accommodate. if (mb_strlen($aPhoneNumber) < mb_strlen($this->nationalNumber)) { return ''; } // Formats the number according to $numberFormat $template = preg_replace('/' . $numberPattern . '/' . PhoneNumberUtil::REGEX_FLAGS, $numberFormat, $aPhoneNumber); // Replaces each digit with character self::$digitPlattern $template = preg_replace('/9/', self::$digitPattern, $template); return $template; }
[ "private", "function", "getFormattingTemplate", "(", "$", "numberPattern", ",", "$", "numberFormat", ")", "{", "// Creates a phone number consisting only of the digit 9 that matches the", "// numberPattern by applying the pattern to the longestPhoneNumber string.", "$", "longestPhoneNumber", "=", "'999999999999999'", ";", "$", "m", "=", "new", "Matcher", "(", "$", "numberPattern", ",", "$", "longestPhoneNumber", ")", ";", "$", "m", "->", "find", "(", ")", ";", "$", "aPhoneNumber", "=", "$", "m", "->", "group", "(", ")", ";", "// No formatting template can be created if the number of digits entered entered so far", "// is longer than the maximum the current formatting rule can accommodate.", "if", "(", "mb_strlen", "(", "$", "aPhoneNumber", ")", "<", "mb_strlen", "(", "$", "this", "->", "nationalNumber", ")", ")", "{", "return", "''", ";", "}", "// Formats the number according to $numberFormat", "$", "template", "=", "preg_replace", "(", "'/'", ".", "$", "numberPattern", ".", "'/'", ".", "PhoneNumberUtil", "::", "REGEX_FLAGS", ",", "$", "numberFormat", ",", "$", "aPhoneNumber", ")", ";", "// Replaces each digit with character self::$digitPlattern", "$", "template", "=", "preg_replace", "(", "'/9/'", ",", "self", "::", "$", "digitPattern", ",", "$", "template", ")", ";", "return", "$", "template", ";", "}" ]
Gets a formatting template which can be used to efficiently format a partial number where digits are added one by one. @param string $numberPattern @param string $numberFormat @return string
[ "Gets", "a", "formatting", "template", "which", "can", "be", "used", "to", "efficiently", "format", "a", "partial", "number", "where", "digits", "are", "added", "one", "by", "one", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L349-L367
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.clear
public function clear() { $this->currentOutput = ''; $this->accruedInput = ''; $this->accruedInputWithoutFormatting = ''; $this->formattingTemplate = ''; $this->lastMatchPosition = 0; $this->currentFormattingPattern = ''; $this->prefixBeforeNationalNumber = ''; $this->extractedNationalPrefix = ''; $this->nationalNumber = ''; $this->ableToFormat = true; $this->inputHasFormatting = false; $this->positionToRemember = 0; $this->originalPosition = 0; $this->isCompleteNumber = false; $this->isExpectingCountryCallingCode = false; $this->possibleFormats = array(); $this->shouldAddSpaceAfterNationalPrefix = false; if ($this->currentMetadata !== $this->defaultMetadata) { $this->currentMetadata = $this->getMetadataForRegion($this->defaultCountry); } }
php
public function clear() { $this->currentOutput = ''; $this->accruedInput = ''; $this->accruedInputWithoutFormatting = ''; $this->formattingTemplate = ''; $this->lastMatchPosition = 0; $this->currentFormattingPattern = ''; $this->prefixBeforeNationalNumber = ''; $this->extractedNationalPrefix = ''; $this->nationalNumber = ''; $this->ableToFormat = true; $this->inputHasFormatting = false; $this->positionToRemember = 0; $this->originalPosition = 0; $this->isCompleteNumber = false; $this->isExpectingCountryCallingCode = false; $this->possibleFormats = array(); $this->shouldAddSpaceAfterNationalPrefix = false; if ($this->currentMetadata !== $this->defaultMetadata) { $this->currentMetadata = $this->getMetadataForRegion($this->defaultCountry); } }
[ "public", "function", "clear", "(", ")", "{", "$", "this", "->", "currentOutput", "=", "''", ";", "$", "this", "->", "accruedInput", "=", "''", ";", "$", "this", "->", "accruedInputWithoutFormatting", "=", "''", ";", "$", "this", "->", "formattingTemplate", "=", "''", ";", "$", "this", "->", "lastMatchPosition", "=", "0", ";", "$", "this", "->", "currentFormattingPattern", "=", "''", ";", "$", "this", "->", "prefixBeforeNationalNumber", "=", "''", ";", "$", "this", "->", "extractedNationalPrefix", "=", "''", ";", "$", "this", "->", "nationalNumber", "=", "''", ";", "$", "this", "->", "ableToFormat", "=", "true", ";", "$", "this", "->", "inputHasFormatting", "=", "false", ";", "$", "this", "->", "positionToRemember", "=", "0", ";", "$", "this", "->", "originalPosition", "=", "0", ";", "$", "this", "->", "isCompleteNumber", "=", "false", ";", "$", "this", "->", "isExpectingCountryCallingCode", "=", "false", ";", "$", "this", "->", "possibleFormats", "=", "array", "(", ")", ";", "$", "this", "->", "shouldAddSpaceAfterNationalPrefix", "=", "false", ";", "if", "(", "$", "this", "->", "currentMetadata", "!==", "$", "this", "->", "defaultMetadata", ")", "{", "$", "this", "->", "currentMetadata", "=", "$", "this", "->", "getMetadataForRegion", "(", "$", "this", "->", "defaultCountry", ")", ";", "}", "}" ]
Clears the internal state of the formatter, so it can be reused.
[ "Clears", "the", "internal", "state", "of", "the", "formatter", "so", "it", "can", "be", "reused", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L372-L394
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.inputDigit
public function inputDigit($nextChar) { $this->currentOutput = $this->inputDigitWithOptionToRememberPosition($nextChar, false); return $this->currentOutput; }
php
public function inputDigit($nextChar) { $this->currentOutput = $this->inputDigitWithOptionToRememberPosition($nextChar, false); return $this->currentOutput; }
[ "public", "function", "inputDigit", "(", "$", "nextChar", ")", "{", "$", "this", "->", "currentOutput", "=", "$", "this", "->", "inputDigitWithOptionToRememberPosition", "(", "$", "nextChar", ",", "false", ")", ";", "return", "$", "this", "->", "currentOutput", ";", "}" ]
Formats a phone number on-the-fly as each digit is entered. @param string $nextChar the most recently entered digit of a phone number. Formatting characters are allowed, but as soon as they are encountered this method foramts the number as entered and not "as you type" anymore. Full width digits and Arabic-indic digits are allowed, and will be shown as they are. @return string The partially formatted phone number
[ "Formats", "a", "phone", "number", "on", "-", "the", "-", "fly", "as", "each", "digit", "is", "entered", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L405-L409
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.ableToExtractLongerNdd
private function ableToExtractLongerNdd() { if (mb_strlen($this->extractedNationalPrefix) > 0) { // Put the extracted NDD back to the national number before attempting to extract a new NDD. $this->nationalNumber = $this->extractedNationalPrefix . $this->nationalNumber; // Remove the previously extracted NDD from prefixBeforeNationalNumber. We cannot simply set // it to empty string because people sometimes incorrectly enter national prefix after the // country code, e.g. +44 (0)20-1234-5678. $indexOfPreviousNdd = mb_strrpos($this->prefixBeforeNationalNumber, $this->extractedNationalPrefix); $this->prefixBeforeNationalNumber = mb_substr(str_pad($this->prefixBeforeNationalNumber, $indexOfPreviousNdd), 0, $indexOfPreviousNdd); } return ($this->extractedNationalPrefix !== $this->removeNationalPrefixFromNationalNumber()); }
php
private function ableToExtractLongerNdd() { if (mb_strlen($this->extractedNationalPrefix) > 0) { // Put the extracted NDD back to the national number before attempting to extract a new NDD. $this->nationalNumber = $this->extractedNationalPrefix . $this->nationalNumber; // Remove the previously extracted NDD from prefixBeforeNationalNumber. We cannot simply set // it to empty string because people sometimes incorrectly enter national prefix after the // country code, e.g. +44 (0)20-1234-5678. $indexOfPreviousNdd = mb_strrpos($this->prefixBeforeNationalNumber, $this->extractedNationalPrefix); $this->prefixBeforeNationalNumber = mb_substr(str_pad($this->prefixBeforeNationalNumber, $indexOfPreviousNdd), 0, $indexOfPreviousNdd); } return ($this->extractedNationalPrefix !== $this->removeNationalPrefixFromNationalNumber()); }
[ "private", "function", "ableToExtractLongerNdd", "(", ")", "{", "if", "(", "mb_strlen", "(", "$", "this", "->", "extractedNationalPrefix", ")", ">", "0", ")", "{", "// Put the extracted NDD back to the national number before attempting to extract a new NDD.", "$", "this", "->", "nationalNumber", "=", "$", "this", "->", "extractedNationalPrefix", ".", "$", "this", "->", "nationalNumber", ";", "// Remove the previously extracted NDD from prefixBeforeNationalNumber. We cannot simply set", "// it to empty string because people sometimes incorrectly enter national prefix after the", "// country code, e.g. +44 (0)20-1234-5678.", "$", "indexOfPreviousNdd", "=", "mb_strrpos", "(", "$", "this", "->", "prefixBeforeNationalNumber", ",", "$", "this", "->", "extractedNationalPrefix", ")", ";", "$", "this", "->", "prefixBeforeNationalNumber", "=", "mb_substr", "(", "str_pad", "(", "$", "this", "->", "prefixBeforeNationalNumber", ",", "$", "indexOfPreviousNdd", ")", ",", "0", ",", "$", "indexOfPreviousNdd", ")", ";", "}", "return", "(", "$", "this", "->", "extractedNationalPrefix", "!==", "$", "this", "->", "removeNationalPrefixFromNationalNumber", "(", ")", ")", ";", "}" ]
Some national prefixes are a substring of others. If extracting the shorter NDD doesn't result in a number we can format, we try to see if we can extract a longer version here. @return bool
[ "Some", "national", "prefixes", "are", "a", "substring", "of", "others", ".", "If", "extracting", "the", "shorter", "NDD", "doesn", "t", "result", "in", "a", "number", "we", "can", "format", "we", "try", "to", "see", "if", "we", "can", "extract", "a", "longer", "version", "here", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L541-L553
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.attemptToFormatAccruedDigits
public function attemptToFormatAccruedDigits() { foreach ($this->possibleFormats as $numberFormat) { $m = new Matcher($numberFormat->getPattern(), $this->nationalNumber); if ($m->matches()) { $nationalPrefixSeparatorsMatcher = new Matcher(self::$nationalPrefixSeparatorsPattern, $numberFormat->getNationalPrefixFormattingRule()); $this->shouldAddSpaceAfterNationalPrefix = $nationalPrefixSeparatorsMatcher->find(); $formattedNumber = $m->replaceAll($numberFormat->getFormat()); return $this->appendNationalNumber($formattedNumber); } } return ''; }
php
public function attemptToFormatAccruedDigits() { foreach ($this->possibleFormats as $numberFormat) { $m = new Matcher($numberFormat->getPattern(), $this->nationalNumber); if ($m->matches()) { $nationalPrefixSeparatorsMatcher = new Matcher(self::$nationalPrefixSeparatorsPattern, $numberFormat->getNationalPrefixFormattingRule()); $this->shouldAddSpaceAfterNationalPrefix = $nationalPrefixSeparatorsMatcher->find(); $formattedNumber = $m->replaceAll($numberFormat->getFormat()); return $this->appendNationalNumber($formattedNumber); } } return ''; }
[ "public", "function", "attemptToFormatAccruedDigits", "(", ")", "{", "foreach", "(", "$", "this", "->", "possibleFormats", "as", "$", "numberFormat", ")", "{", "$", "m", "=", "new", "Matcher", "(", "$", "numberFormat", "->", "getPattern", "(", ")", ",", "$", "this", "->", "nationalNumber", ")", ";", "if", "(", "$", "m", "->", "matches", "(", ")", ")", "{", "$", "nationalPrefixSeparatorsMatcher", "=", "new", "Matcher", "(", "self", "::", "$", "nationalPrefixSeparatorsPattern", ",", "$", "numberFormat", "->", "getNationalPrefixFormattingRule", "(", ")", ")", ";", "$", "this", "->", "shouldAddSpaceAfterNationalPrefix", "=", "$", "nationalPrefixSeparatorsMatcher", "->", "find", "(", ")", ";", "$", "formattedNumber", "=", "$", "m", "->", "replaceAll", "(", "$", "numberFormat", "->", "getFormat", "(", ")", ")", ";", "return", "$", "this", "->", "appendNationalNumber", "(", "$", "formattedNumber", ")", ";", "}", "}", "return", "''", ";", "}" ]
Checks to see if there is an exact pattern match for these digits. If so, we should use this instead of any other formatting template whose leadingDigitsPattern also matches the input. @return string
[ "Checks", "to", "see", "if", "there", "is", "an", "exact", "pattern", "match", "for", "these", "digits", ".", "If", "so", "we", "should", "use", "this", "instead", "of", "any", "other", "formatting", "template", "whose", "leadingDigitsPattern", "also", "matches", "the", "input", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L573-L585
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.attemptToChooseFormattingPattern
private function attemptToChooseFormattingPattern() { // We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national // number (excluding national prefix) have been entered. if (mb_strlen($this->nationalNumber) >= self::$minLeadingDigitsLength) { $this->getAvailableFormats($this->nationalNumber); // See if the accrued digits can be formatted properly already. $formattedNumber = $this->attemptToFormatAccruedDigits(); if (mb_strlen($formattedNumber) > 0) { return $formattedNumber; } return $this->maybeCreateNewTemplate() ? $this->inputAccruedNationalNumber() : $this->accruedInput; } return $this->appendNationalNumber($this->nationalNumber); }
php
private function attemptToChooseFormattingPattern() { // We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national // number (excluding national prefix) have been entered. if (mb_strlen($this->nationalNumber) >= self::$minLeadingDigitsLength) { $this->getAvailableFormats($this->nationalNumber); // See if the accrued digits can be formatted properly already. $formattedNumber = $this->attemptToFormatAccruedDigits(); if (mb_strlen($formattedNumber) > 0) { return $formattedNumber; } return $this->maybeCreateNewTemplate() ? $this->inputAccruedNationalNumber() : $this->accruedInput; } return $this->appendNationalNumber($this->nationalNumber); }
[ "private", "function", "attemptToChooseFormattingPattern", "(", ")", "{", "// We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national", "// number (excluding national prefix) have been entered.", "if", "(", "mb_strlen", "(", "$", "this", "->", "nationalNumber", ")", ">=", "self", "::", "$", "minLeadingDigitsLength", ")", "{", "$", "this", "->", "getAvailableFormats", "(", "$", "this", "->", "nationalNumber", ")", ";", "// See if the accrued digits can be formatted properly already.", "$", "formattedNumber", "=", "$", "this", "->", "attemptToFormatAccruedDigits", "(", ")", ";", "if", "(", "mb_strlen", "(", "$", "formattedNumber", ")", ">", "0", ")", "{", "return", "$", "formattedNumber", ";", "}", "return", "$", "this", "->", "maybeCreateNewTemplate", "(", ")", "?", "$", "this", "->", "inputAccruedNationalNumber", "(", ")", ":", "$", "this", "->", "accruedInput", ";", "}", "return", "$", "this", "->", "appendNationalNumber", "(", "$", "this", "->", "nationalNumber", ")", ";", "}" ]
Attempts to set the formatting template and returns a string which contains the formatted version of the digits entered so far. @return string
[ "Attempts", "to", "set", "the", "formatting", "template", "and", "returns", "a", "string", "which", "contains", "the", "formatted", "version", "of", "the", "digits", "entered", "so", "far", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L638-L653
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.inputAccruedNationalNumber
private function inputAccruedNationalNumber() { $lengthOfNationalNumber = mb_strlen($this->nationalNumber); if ($lengthOfNationalNumber > 0) { $tempNationalNumber = ''; for ($i = 0; $i < $lengthOfNationalNumber; $i++) { $tempNationalNumber = $this->inputDigitHelper(mb_substr($this->nationalNumber, $i, 1)); } return $this->ableToFormat ? $this->appendNationalNumber($tempNationalNumber) : $this->accruedInput; } return $this->prefixBeforeNationalNumber; }
php
private function inputAccruedNationalNumber() { $lengthOfNationalNumber = mb_strlen($this->nationalNumber); if ($lengthOfNationalNumber > 0) { $tempNationalNumber = ''; for ($i = 0; $i < $lengthOfNationalNumber; $i++) { $tempNationalNumber = $this->inputDigitHelper(mb_substr($this->nationalNumber, $i, 1)); } return $this->ableToFormat ? $this->appendNationalNumber($tempNationalNumber) : $this->accruedInput; } return $this->prefixBeforeNationalNumber; }
[ "private", "function", "inputAccruedNationalNumber", "(", ")", "{", "$", "lengthOfNationalNumber", "=", "mb_strlen", "(", "$", "this", "->", "nationalNumber", ")", ";", "if", "(", "$", "lengthOfNationalNumber", ">", "0", ")", "{", "$", "tempNationalNumber", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "lengthOfNationalNumber", ";", "$", "i", "++", ")", "{", "$", "tempNationalNumber", "=", "$", "this", "->", "inputDigitHelper", "(", "mb_substr", "(", "$", "this", "->", "nationalNumber", ",", "$", "i", ",", "1", ")", ")", ";", "}", "return", "$", "this", "->", "ableToFormat", "?", "$", "this", "->", "appendNationalNumber", "(", "$", "tempNationalNumber", ")", ":", "$", "this", "->", "accruedInput", ";", "}", "return", "$", "this", "->", "prefixBeforeNationalNumber", ";", "}" ]
Invokes inputDigitHelper on each digit of the national number accrued, and returns a formatted string in the end @return string
[ "Invokes", "inputDigitHelper", "on", "each", "digit", "of", "the", "national", "number", "accrued", "and", "returns", "a", "formatted", "string", "in", "the", "end" ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L660-L672
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.isNanpaNumberWithNationalPrefix
private function isNanpaNumberWithNationalPrefix() { // For NANPA numbers beginning with 1[2-9], treat the 1 as the national prefix. The reason is // that national significant numbers in NANPA always start with [2-9] after the national prefix. // Numbers beginning with 1[01] can only be short/emergency numbers, which don't need the // national prefix. return ($this->currentMetadata->getCountryCode() == 1) && (mb_substr($this->nationalNumber, 0, 1) == '1') && (mb_substr($this->nationalNumber, 1, 1) != '0') && (mb_substr($this->nationalNumber, 1, 1) != '1'); }
php
private function isNanpaNumberWithNationalPrefix() { // For NANPA numbers beginning with 1[2-9], treat the 1 as the national prefix. The reason is // that national significant numbers in NANPA always start with [2-9] after the national prefix. // Numbers beginning with 1[01] can only be short/emergency numbers, which don't need the // national prefix. return ($this->currentMetadata->getCountryCode() == 1) && (mb_substr($this->nationalNumber, 0, 1) == '1') && (mb_substr($this->nationalNumber, 1, 1) != '0') && (mb_substr($this->nationalNumber, 1, 1) != '1'); }
[ "private", "function", "isNanpaNumberWithNationalPrefix", "(", ")", "{", "// For NANPA numbers beginning with 1[2-9], treat the 1 as the national prefix. The reason is", "// that national significant numbers in NANPA always start with [2-9] after the national prefix.", "// Numbers beginning with 1[01] can only be short/emergency numbers, which don't need the", "// national prefix.", "return", "(", "$", "this", "->", "currentMetadata", "->", "getCountryCode", "(", ")", "==", "1", ")", "&&", "(", "mb_substr", "(", "$", "this", "->", "nationalNumber", ",", "0", ",", "1", ")", "==", "'1'", ")", "&&", "(", "mb_substr", "(", "$", "this", "->", "nationalNumber", ",", "1", ",", "1", ")", "!=", "'0'", ")", "&&", "(", "mb_substr", "(", "$", "this", "->", "nationalNumber", ",", "1", ",", "1", ")", "!=", "'1'", ")", ";", "}" ]
Returns true if the current country is a NANPA country and the national number beings with the national prefix @return bool
[ "Returns", "true", "if", "the", "current", "country", "is", "a", "NANPA", "country", "and", "the", "national", "number", "beings", "with", "the", "national", "prefix" ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L679-L687
train
giggsey/libphonenumber-for-php
src/AsYouTypeFormatter.php
AsYouTypeFormatter.removeNationalPrefixFromNationalNumber
private function removeNationalPrefixFromNationalNumber() { $startOfNationalNumber = 0; if ($this->isNanpaNumberWithNationalPrefix()) { $startOfNationalNumber = 1; $this->prefixBeforeNationalNumber .= '1' . self::$seperatorBeforeNationalNumber; $this->isCompleteNumber = true; } elseif ($this->currentMetadata->hasNationalPrefixForParsing()) { $m = new Matcher($this->currentMetadata->getNationalPrefixForParsing(), $this->nationalNumber); // Since some national prefix patterns are entirely optional, check that a national prefix // could actually be extracted. if ($m->lookingAt() && $m->end() > 0) { // When the national prefix is detected, we use international formatting rules instead of // national ones, because national formatting rules could contain local formatting rules // for numbers entered without area code. $this->isCompleteNumber = true; $startOfNationalNumber = $m->end(); $this->prefixBeforeNationalNumber .= mb_substr($this->nationalNumber, 0, $startOfNationalNumber); } } $nationalPrefix = mb_substr($this->nationalNumber, 0, $startOfNationalNumber); $this->nationalNumber = mb_substr($this->nationalNumber, $startOfNationalNumber); return $nationalPrefix; }
php
private function removeNationalPrefixFromNationalNumber() { $startOfNationalNumber = 0; if ($this->isNanpaNumberWithNationalPrefix()) { $startOfNationalNumber = 1; $this->prefixBeforeNationalNumber .= '1' . self::$seperatorBeforeNationalNumber; $this->isCompleteNumber = true; } elseif ($this->currentMetadata->hasNationalPrefixForParsing()) { $m = new Matcher($this->currentMetadata->getNationalPrefixForParsing(), $this->nationalNumber); // Since some national prefix patterns are entirely optional, check that a national prefix // could actually be extracted. if ($m->lookingAt() && $m->end() > 0) { // When the national prefix is detected, we use international formatting rules instead of // national ones, because national formatting rules could contain local formatting rules // for numbers entered without area code. $this->isCompleteNumber = true; $startOfNationalNumber = $m->end(); $this->prefixBeforeNationalNumber .= mb_substr($this->nationalNumber, 0, $startOfNationalNumber); } } $nationalPrefix = mb_substr($this->nationalNumber, 0, $startOfNationalNumber); $this->nationalNumber = mb_substr($this->nationalNumber, $startOfNationalNumber); return $nationalPrefix; }
[ "private", "function", "removeNationalPrefixFromNationalNumber", "(", ")", "{", "$", "startOfNationalNumber", "=", "0", ";", "if", "(", "$", "this", "->", "isNanpaNumberWithNationalPrefix", "(", ")", ")", "{", "$", "startOfNationalNumber", "=", "1", ";", "$", "this", "->", "prefixBeforeNationalNumber", ".=", "'1'", ".", "self", "::", "$", "seperatorBeforeNationalNumber", ";", "$", "this", "->", "isCompleteNumber", "=", "true", ";", "}", "elseif", "(", "$", "this", "->", "currentMetadata", "->", "hasNationalPrefixForParsing", "(", ")", ")", "{", "$", "m", "=", "new", "Matcher", "(", "$", "this", "->", "currentMetadata", "->", "getNationalPrefixForParsing", "(", ")", ",", "$", "this", "->", "nationalNumber", ")", ";", "// Since some national prefix patterns are entirely optional, check that a national prefix", "// could actually be extracted.", "if", "(", "$", "m", "->", "lookingAt", "(", ")", "&&", "$", "m", "->", "end", "(", ")", ">", "0", ")", "{", "// When the national prefix is detected, we use international formatting rules instead of", "// national ones, because national formatting rules could contain local formatting rules", "// for numbers entered without area code.", "$", "this", "->", "isCompleteNumber", "=", "true", ";", "$", "startOfNationalNumber", "=", "$", "m", "->", "end", "(", ")", ";", "$", "this", "->", "prefixBeforeNationalNumber", ".=", "mb_substr", "(", "$", "this", "->", "nationalNumber", ",", "0", ",", "$", "startOfNationalNumber", ")", ";", "}", "}", "$", "nationalPrefix", "=", "mb_substr", "(", "$", "this", "->", "nationalNumber", ",", "0", ",", "$", "startOfNationalNumber", ")", ";", "$", "this", "->", "nationalNumber", "=", "mb_substr", "(", "$", "this", "->", "nationalNumber", ",", "$", "startOfNationalNumber", ")", ";", "return", "$", "nationalPrefix", ";", "}" ]
Returns the national prefix extracted, or an empty string if it is not present. @return string
[ "Returns", "the", "national", "prefix", "extracted", "or", "an", "empty", "string", "if", "it", "is", "not", "present", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/AsYouTypeFormatter.php#L693-L716
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.normalizeHelper
protected static function normalizeHelper($number, array $normalizationReplacements, $removeNonMatches) { $normalizedNumber = ''; $strLength = mb_strlen($number, 'UTF-8'); for ($i = 0; $i < $strLength; $i++) { $character = mb_substr($number, $i, 1, 'UTF-8'); if (isset($normalizationReplacements[mb_strtoupper($character, 'UTF-8')])) { $normalizedNumber .= $normalizationReplacements[mb_strtoupper($character, 'UTF-8')]; } elseif (!$removeNonMatches) { $normalizedNumber .= $character; } // If neither of the above are true, we remove this character. } return $normalizedNumber; }
php
protected static function normalizeHelper($number, array $normalizationReplacements, $removeNonMatches) { $normalizedNumber = ''; $strLength = mb_strlen($number, 'UTF-8'); for ($i = 0; $i < $strLength; $i++) { $character = mb_substr($number, $i, 1, 'UTF-8'); if (isset($normalizationReplacements[mb_strtoupper($character, 'UTF-8')])) { $normalizedNumber .= $normalizationReplacements[mb_strtoupper($character, 'UTF-8')]; } elseif (!$removeNonMatches) { $normalizedNumber .= $character; } // If neither of the above are true, we remove this character. } return $normalizedNumber; }
[ "protected", "static", "function", "normalizeHelper", "(", "$", "number", ",", "array", "$", "normalizationReplacements", ",", "$", "removeNonMatches", ")", "{", "$", "normalizedNumber", "=", "''", ";", "$", "strLength", "=", "mb_strlen", "(", "$", "number", ",", "'UTF-8'", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "strLength", ";", "$", "i", "++", ")", "{", "$", "character", "=", "mb_substr", "(", "$", "number", ",", "$", "i", ",", "1", ",", "'UTF-8'", ")", ";", "if", "(", "isset", "(", "$", "normalizationReplacements", "[", "mb_strtoupper", "(", "$", "character", ",", "'UTF-8'", ")", "]", ")", ")", "{", "$", "normalizedNumber", ".=", "$", "normalizationReplacements", "[", "mb_strtoupper", "(", "$", "character", ",", "'UTF-8'", ")", "]", ";", "}", "elseif", "(", "!", "$", "removeNonMatches", ")", "{", "$", "normalizedNumber", ".=", "$", "character", ";", "}", "// If neither of the above are true, we remove this character.", "}", "return", "$", "normalizedNumber", ";", "}" ]
Normalizes a string of characters representing a phone number by replacing all characters found in the accompanying map with the values therein, and stripping all other characters if removeNonMatches is true. @param string $number a string of characters representing a phone number @param array $normalizationReplacements a mapping of characters to what they should be replaced by in the normalized version of the phone number @param bool $removeNonMatches indicates whether characters that are not able to be replaced should be stripped from the number. If this is false, they will be left unchanged in the number. @return string the normalized string version of the phone number
[ "Normalizes", "a", "string", "of", "characters", "representing", "a", "phone", "number", "by", "replacing", "all", "characters", "found", "in", "the", "accompanying", "map", "with", "the", "values", "therein", "and", "stripping", "all", "other", "characters", "if", "removeNonMatches", "is", "true", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L580-L594
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.formattingRuleHasFirstGroupOnly
public static function formattingRuleHasFirstGroupOnly($nationalPrefixFormattingRule) { $firstGroupOnlyPrefixPatternMatcher = new Matcher(static::FIRST_GROUP_ONLY_PREFIX_PATTERN, $nationalPrefixFormattingRule); return mb_strlen($nationalPrefixFormattingRule) === 0 || $firstGroupOnlyPrefixPatternMatcher->matches(); }
php
public static function formattingRuleHasFirstGroupOnly($nationalPrefixFormattingRule) { $firstGroupOnlyPrefixPatternMatcher = new Matcher(static::FIRST_GROUP_ONLY_PREFIX_PATTERN, $nationalPrefixFormattingRule); return mb_strlen($nationalPrefixFormattingRule) === 0 || $firstGroupOnlyPrefixPatternMatcher->matches(); }
[ "public", "static", "function", "formattingRuleHasFirstGroupOnly", "(", "$", "nationalPrefixFormattingRule", ")", "{", "$", "firstGroupOnlyPrefixPatternMatcher", "=", "new", "Matcher", "(", "static", "::", "FIRST_GROUP_ONLY_PREFIX_PATTERN", ",", "$", "nationalPrefixFormattingRule", ")", ";", "return", "mb_strlen", "(", "$", "nationalPrefixFormattingRule", ")", "===", "0", "||", "$", "firstGroupOnlyPrefixPatternMatcher", "->", "matches", "(", ")", ";", "}" ]
Helper function to check if the national prefix formatting rule has the first group only, i.e., does not start with the national prefix. @param string $nationalPrefixFormattingRule @return bool
[ "Helper", "function", "to", "check", "if", "the", "national", "prefix", "formatting", "rule", "has", "the", "first", "group", "only", "i", ".", "e", ".", "does", "not", "start", "with", "the", "national", "prefix", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L602-L609
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.getSupportedTypesForMetadata
private function getSupportedTypesForMetadata(PhoneMetadata $metadata) { $types = array(); foreach (array_keys(PhoneNumberType::values()) as $type) { if ($type === PhoneNumberType::FIXED_LINE_OR_MOBILE || $type === PhoneNumberType::UNKNOWN) { // Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a // particular number type can't be determined) or UNKNOWN (the non-type). continue; } if (self::descHasData($this->getNumberDescByType($metadata, $type))) { $types[] = $type; } } return $types; }
php
private function getSupportedTypesForMetadata(PhoneMetadata $metadata) { $types = array(); foreach (array_keys(PhoneNumberType::values()) as $type) { if ($type === PhoneNumberType::FIXED_LINE_OR_MOBILE || $type === PhoneNumberType::UNKNOWN) { // Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a // particular number type can't be determined) or UNKNOWN (the non-type). continue; } if (self::descHasData($this->getNumberDescByType($metadata, $type))) { $types[] = $type; } } return $types; }
[ "private", "function", "getSupportedTypesForMetadata", "(", "PhoneMetadata", "$", "metadata", ")", "{", "$", "types", "=", "array", "(", ")", ";", "foreach", "(", "array_keys", "(", "PhoneNumberType", "::", "values", "(", ")", ")", "as", "$", "type", ")", "{", "if", "(", "$", "type", "===", "PhoneNumberType", "::", "FIXED_LINE_OR_MOBILE", "||", "$", "type", "===", "PhoneNumberType", "::", "UNKNOWN", ")", "{", "// Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a", "// particular number type can't be determined) or UNKNOWN (the non-type).", "continue", ";", "}", "if", "(", "self", "::", "descHasData", "(", "$", "this", "->", "getNumberDescByType", "(", "$", "metadata", ",", "$", "type", ")", ")", ")", "{", "$", "types", "[", "]", "=", "$", "type", ";", "}", "}", "return", "$", "types", ";", "}" ]
Returns the types we have metadata for based on the PhoneMetadata object passed in @param PhoneMetadata $metadata @return array
[ "Returns", "the", "types", "we", "have", "metadata", "for", "based", "on", "the", "PhoneMetadata", "object", "passed", "in" ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L684-L700
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.getNationalSignificantNumber
public function getNationalSignificantNumber(PhoneNumber $number) { // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix. $nationalNumber = ''; if ($number->isItalianLeadingZero() && $number->getNumberOfLeadingZeros() > 0) { $zeros = str_repeat('0', $number->getNumberOfLeadingZeros()); $nationalNumber .= $zeros; } $nationalNumber .= $number->getNationalNumber(); return $nationalNumber; }
php
public function getNationalSignificantNumber(PhoneNumber $number) { // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix. $nationalNumber = ''; if ($number->isItalianLeadingZero() && $number->getNumberOfLeadingZeros() > 0) { $zeros = str_repeat('0', $number->getNumberOfLeadingZeros()); $nationalNumber .= $zeros; } $nationalNumber .= $number->getNationalNumber(); return $nationalNumber; }
[ "public", "function", "getNationalSignificantNumber", "(", "PhoneNumber", "$", "number", ")", "{", "// If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.", "$", "nationalNumber", "=", "''", ";", "if", "(", "$", "number", "->", "isItalianLeadingZero", "(", ")", "&&", "$", "number", "->", "getNumberOfLeadingZeros", "(", ")", ">", "0", ")", "{", "$", "zeros", "=", "str_repeat", "(", "'0'", ",", "$", "number", "->", "getNumberOfLeadingZeros", "(", ")", ")", ";", "$", "nationalNumber", ".=", "$", "zeros", ";", "}", "$", "nationalNumber", ".=", "$", "number", "->", "getNationalNumber", "(", ")", ";", "return", "$", "nationalNumber", ";", "}" ]
Gets the national significant number of the a phone number. Note a national significant number doesn't contain a national prefix or any formatting. @param PhoneNumber $number the phone number for which the national significant number is needed @return string the national significant number of the PhoneNumber object passed in
[ "Gets", "the", "national", "significant", "number", "of", "the", "a", "phone", "number", ".", "Note", "a", "national", "significant", "number", "doesn", "t", "contain", "a", "national", "prefix", "or", "any", "formatting", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L893-L903
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.getNumberType
public function getNumberType(PhoneNumber $number) { $regionCode = $this->getRegionCodeForNumber($number); $metadata = $this->getMetadataForRegionOrCallingCode($number->getCountryCode(), $regionCode); if ($metadata === null) { return PhoneNumberType::UNKNOWN; } $nationalSignificantNumber = $this->getNationalSignificantNumber($number); return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata); }
php
public function getNumberType(PhoneNumber $number) { $regionCode = $this->getRegionCodeForNumber($number); $metadata = $this->getMetadataForRegionOrCallingCode($number->getCountryCode(), $regionCode); if ($metadata === null) { return PhoneNumberType::UNKNOWN; } $nationalSignificantNumber = $this->getNationalSignificantNumber($number); return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata); }
[ "public", "function", "getNumberType", "(", "PhoneNumber", "$", "number", ")", "{", "$", "regionCode", "=", "$", "this", "->", "getRegionCodeForNumber", "(", "$", "number", ")", ";", "$", "metadata", "=", "$", "this", "->", "getMetadataForRegionOrCallingCode", "(", "$", "number", "->", "getCountryCode", "(", ")", ",", "$", "regionCode", ")", ";", "if", "(", "$", "metadata", "===", "null", ")", "{", "return", "PhoneNumberType", "::", "UNKNOWN", ";", "}", "$", "nationalSignificantNumber", "=", "$", "this", "->", "getNationalSignificantNumber", "(", "$", "number", ")", ";", "return", "$", "this", "->", "getNumberTypeHelper", "(", "$", "nationalSignificantNumber", ",", "$", "metadata", ")", ";", "}" ]
Gets the type of a valid phone number. @param PhoneNumber $number the number the phone number that we want to know the type @return int PhoneNumberType the type of the phone number, or UNKNOWN if it is invalid
[ "Gets", "the", "type", "of", "a", "valid", "phone", "number", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L1017-L1026
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.format
public function format(PhoneNumber $number, $numberFormat) { if ($number->getNationalNumber() == 0 && $number->hasRawInput()) { // Unparseable numbers that kept their raw input just use that. // This is the only case where a number can be formatted as E164 without a // leading '+' symbol (but the original number wasn't parseable anyway). // TODO: Consider removing the 'if' above so that unparseable // strings without raw input format to the empty string instead of "+00" $rawInput = $number->getRawInput(); if (mb_strlen($rawInput) > 0) { return $rawInput; } } $formattedNumber = ''; $countryCallingCode = $number->getCountryCode(); $nationalSignificantNumber = $this->getNationalSignificantNumber($number); if ($numberFormat == PhoneNumberFormat::E164) { // Early exit for E164 case (even if the country calling code is invalid) since no formatting // of the national number needs to be applied. Extensions are not formatted. $formattedNumber .= $nationalSignificantNumber; $this->prefixNumberWithCountryCallingCode($countryCallingCode, PhoneNumberFormat::E164, $formattedNumber); return $formattedNumber; } if (!$this->hasValidCountryCallingCode($countryCallingCode)) { $formattedNumber .= $nationalSignificantNumber; return $formattedNumber; } // Note getRegionCodeForCountryCode() is used because formatting information for regions which // share a country calling code is contained by only one region for performance reasons. For // example, for NANPA regions it will be contained in the metadata for US. $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); // Metadata cannot be null because the country calling code is valid (which means that the // region code cannot be ZZ and must be one of our supported region codes). $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode); $formattedNumber .= $this->formatNsn($nationalSignificantNumber, $metadata, $numberFormat); $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber); $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber); return $formattedNumber; }
php
public function format(PhoneNumber $number, $numberFormat) { if ($number->getNationalNumber() == 0 && $number->hasRawInput()) { // Unparseable numbers that kept their raw input just use that. // This is the only case where a number can be formatted as E164 without a // leading '+' symbol (but the original number wasn't parseable anyway). // TODO: Consider removing the 'if' above so that unparseable // strings without raw input format to the empty string instead of "+00" $rawInput = $number->getRawInput(); if (mb_strlen($rawInput) > 0) { return $rawInput; } } $formattedNumber = ''; $countryCallingCode = $number->getCountryCode(); $nationalSignificantNumber = $this->getNationalSignificantNumber($number); if ($numberFormat == PhoneNumberFormat::E164) { // Early exit for E164 case (even if the country calling code is invalid) since no formatting // of the national number needs to be applied. Extensions are not formatted. $formattedNumber .= $nationalSignificantNumber; $this->prefixNumberWithCountryCallingCode($countryCallingCode, PhoneNumberFormat::E164, $formattedNumber); return $formattedNumber; } if (!$this->hasValidCountryCallingCode($countryCallingCode)) { $formattedNumber .= $nationalSignificantNumber; return $formattedNumber; } // Note getRegionCodeForCountryCode() is used because formatting information for regions which // share a country calling code is contained by only one region for performance reasons. For // example, for NANPA regions it will be contained in the metadata for US. $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); // Metadata cannot be null because the country calling code is valid (which means that the // region code cannot be ZZ and must be one of our supported region codes). $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode); $formattedNumber .= $this->formatNsn($nationalSignificantNumber, $metadata, $numberFormat); $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber); $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber); return $formattedNumber; }
[ "public", "function", "format", "(", "PhoneNumber", "$", "number", ",", "$", "numberFormat", ")", "{", "if", "(", "$", "number", "->", "getNationalNumber", "(", ")", "==", "0", "&&", "$", "number", "->", "hasRawInput", "(", ")", ")", "{", "// Unparseable numbers that kept their raw input just use that.", "// This is the only case where a number can be formatted as E164 without a", "// leading '+' symbol (but the original number wasn't parseable anyway).", "// TODO: Consider removing the 'if' above so that unparseable", "// strings without raw input format to the empty string instead of \"+00\"", "$", "rawInput", "=", "$", "number", "->", "getRawInput", "(", ")", ";", "if", "(", "mb_strlen", "(", "$", "rawInput", ")", ">", "0", ")", "{", "return", "$", "rawInput", ";", "}", "}", "$", "formattedNumber", "=", "''", ";", "$", "countryCallingCode", "=", "$", "number", "->", "getCountryCode", "(", ")", ";", "$", "nationalSignificantNumber", "=", "$", "this", "->", "getNationalSignificantNumber", "(", "$", "number", ")", ";", "if", "(", "$", "numberFormat", "==", "PhoneNumberFormat", "::", "E164", ")", "{", "// Early exit for E164 case (even if the country calling code is invalid) since no formatting", "// of the national number needs to be applied. Extensions are not formatted.", "$", "formattedNumber", ".=", "$", "nationalSignificantNumber", ";", "$", "this", "->", "prefixNumberWithCountryCallingCode", "(", "$", "countryCallingCode", ",", "PhoneNumberFormat", "::", "E164", ",", "$", "formattedNumber", ")", ";", "return", "$", "formattedNumber", ";", "}", "if", "(", "!", "$", "this", "->", "hasValidCountryCallingCode", "(", "$", "countryCallingCode", ")", ")", "{", "$", "formattedNumber", ".=", "$", "nationalSignificantNumber", ";", "return", "$", "formattedNumber", ";", "}", "// Note getRegionCodeForCountryCode() is used because formatting information for regions which", "// share a country calling code is contained by only one region for performance reasons. For", "// example, for NANPA regions it will be contained in the metadata for US.", "$", "regionCode", "=", "$", "this", "->", "getRegionCodeForCountryCode", "(", "$", "countryCallingCode", ")", ";", "// Metadata cannot be null because the country calling code is valid (which means that the", "// region code cannot be ZZ and must be one of our supported region codes).", "$", "metadata", "=", "$", "this", "->", "getMetadataForRegionOrCallingCode", "(", "$", "countryCallingCode", ",", "$", "regionCode", ")", ";", "$", "formattedNumber", ".=", "$", "this", "->", "formatNsn", "(", "$", "nationalSignificantNumber", ",", "$", "metadata", ",", "$", "numberFormat", ")", ";", "$", "this", "->", "maybeAppendFormattedExtension", "(", "$", "number", ",", "$", "metadata", ",", "$", "numberFormat", ",", "$", "formattedNumber", ")", ";", "$", "this", "->", "prefixNumberWithCountryCallingCode", "(", "$", "countryCallingCode", ",", "$", "numberFormat", ",", "$", "formattedNumber", ")", ";", "return", "$", "formattedNumber", ";", "}" ]
Formats a phone number in the specified format using default rules. Note that this does not promise to produce a phone number that the user can dial from where they are - although we do format in either 'national' or 'international' format depending on what the client asks for, we do not currently support a more abbreviated format, such as for users in the same "area" who could potentially dial the number without area code. Note that if the phone number has a country calling code of 0 or an otherwise invalid country calling code, we cannot work out which formatting rules to apply so we return the national significant number with no formatting applied. @param PhoneNumber $number the phone number to be formatted @param int $numberFormat the PhoneNumberFormat the phone number should be formatted into @return string the formatted phone number
[ "Formats", "a", "phone", "number", "in", "the", "specified", "format", "using", "default", "rules", ".", "Note", "that", "this", "does", "not", "promise", "to", "produce", "a", "phone", "number", "that", "the", "user", "can", "dial", "from", "where", "they", "are", "-", "although", "we", "do", "format", "in", "either", "national", "or", "international", "format", "depending", "on", "what", "the", "client", "asks", "for", "we", "do", "not", "currently", "support", "a", "more", "abbreviated", "format", "such", "as", "for", "users", "in", "the", "same", "area", "who", "could", "potentially", "dial", "the", "number", "without", "area", "code", ".", "Note", "that", "if", "the", "phone", "number", "has", "a", "country", "calling", "code", "of", "0", "or", "an", "otherwise", "invalid", "country", "calling", "code", "we", "cannot", "work", "out", "which", "formatting", "rules", "to", "apply", "so", "we", "return", "the", "national", "significant", "number", "with", "no", "formatting", "applied", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L1137-L1179
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.prefixNumberWithCountryCallingCode
protected function prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, &$formattedNumber) { switch ($numberFormat) { case PhoneNumberFormat::E164: $formattedNumber = static::PLUS_SIGN . $countryCallingCode . $formattedNumber; return; case PhoneNumberFormat::INTERNATIONAL: $formattedNumber = static::PLUS_SIGN . $countryCallingCode . ' ' . $formattedNumber; return; case PhoneNumberFormat::RFC3966: $formattedNumber = static::RFC3966_PREFIX . static::PLUS_SIGN . $countryCallingCode . '-' . $formattedNumber; return; case PhoneNumberFormat::NATIONAL: default: return; } }
php
protected function prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, &$formattedNumber) { switch ($numberFormat) { case PhoneNumberFormat::E164: $formattedNumber = static::PLUS_SIGN . $countryCallingCode . $formattedNumber; return; case PhoneNumberFormat::INTERNATIONAL: $formattedNumber = static::PLUS_SIGN . $countryCallingCode . ' ' . $formattedNumber; return; case PhoneNumberFormat::RFC3966: $formattedNumber = static::RFC3966_PREFIX . static::PLUS_SIGN . $countryCallingCode . '-' . $formattedNumber; return; case PhoneNumberFormat::NATIONAL: default: return; } }
[ "protected", "function", "prefixNumberWithCountryCallingCode", "(", "$", "countryCallingCode", ",", "$", "numberFormat", ",", "&", "$", "formattedNumber", ")", "{", "switch", "(", "$", "numberFormat", ")", "{", "case", "PhoneNumberFormat", "::", "E164", ":", "$", "formattedNumber", "=", "static", "::", "PLUS_SIGN", ".", "$", "countryCallingCode", ".", "$", "formattedNumber", ";", "return", ";", "case", "PhoneNumberFormat", "::", "INTERNATIONAL", ":", "$", "formattedNumber", "=", "static", "::", "PLUS_SIGN", ".", "$", "countryCallingCode", ".", "' '", ".", "$", "formattedNumber", ";", "return", ";", "case", "PhoneNumberFormat", "::", "RFC3966", ":", "$", "formattedNumber", "=", "static", "::", "RFC3966_PREFIX", ".", "static", "::", "PLUS_SIGN", ".", "$", "countryCallingCode", ".", "'-'", ".", "$", "formattedNumber", ";", "return", ";", "case", "PhoneNumberFormat", "::", "NATIONAL", ":", "default", ":", "return", ";", "}", "}" ]
A helper function that is used by format and formatByPattern. @param int $countryCallingCode @param int $numberFormat PhoneNumberFormat @param string $formattedNumber
[ "A", "helper", "function", "that", "is", "used", "by", "format", "and", "formatByPattern", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L1187-L1203
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.formatNsnUsingPattern
public function formatNsnUsingPattern( $nationalNumber, NumberFormat $formattingPattern, $numberFormat, $carrierCode = null ) { $numberFormatRule = $formattingPattern->getFormat(); $m = new Matcher($formattingPattern->getPattern(), $nationalNumber); if ($numberFormat === PhoneNumberFormat::NATIONAL && $carrierCode !== null && mb_strlen($carrierCode) > 0 && mb_strlen($formattingPattern->getDomesticCarrierCodeFormattingRule()) > 0 ) { // Replace the $CC in the formatting rule with the desired carrier code. $carrierCodeFormattingRule = $formattingPattern->getDomesticCarrierCodeFormattingRule(); $carrierCodeFormattingRule = str_replace(static::CC_STRING, $carrierCode, $carrierCodeFormattingRule); // Now replace the $FG in the formatting rule with the first group and the carrier code // combined in the appropriate way. $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule); $numberFormatRule = $firstGroupMatcher->replaceFirst($carrierCodeFormattingRule); $formattedNationalNumber = $m->replaceAll($numberFormatRule); } else { // Use the national prefix formatting rule instead. $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule(); if ($numberFormat == PhoneNumberFormat::NATIONAL && $nationalPrefixFormattingRule !== null && mb_strlen($nationalPrefixFormattingRule) > 0 ) { $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule); $formattedNationalNumber = $m->replaceAll( $firstGroupMatcher->replaceFirst($nationalPrefixFormattingRule) ); } else { $formattedNationalNumber = $m->replaceAll($numberFormatRule); } } if ($numberFormat == PhoneNumberFormat::RFC3966) { // Strip any leading punctuation. $matcher = new Matcher(static::$SEPARATOR_PATTERN, $formattedNationalNumber); if ($matcher->lookingAt()) { $formattedNationalNumber = $matcher->replaceFirst(''); } // Replace the rest with a dash between each number group. $formattedNationalNumber = $matcher->reset($formattedNationalNumber)->replaceAll('-'); } return $formattedNationalNumber; }
php
public function formatNsnUsingPattern( $nationalNumber, NumberFormat $formattingPattern, $numberFormat, $carrierCode = null ) { $numberFormatRule = $formattingPattern->getFormat(); $m = new Matcher($formattingPattern->getPattern(), $nationalNumber); if ($numberFormat === PhoneNumberFormat::NATIONAL && $carrierCode !== null && mb_strlen($carrierCode) > 0 && mb_strlen($formattingPattern->getDomesticCarrierCodeFormattingRule()) > 0 ) { // Replace the $CC in the formatting rule with the desired carrier code. $carrierCodeFormattingRule = $formattingPattern->getDomesticCarrierCodeFormattingRule(); $carrierCodeFormattingRule = str_replace(static::CC_STRING, $carrierCode, $carrierCodeFormattingRule); // Now replace the $FG in the formatting rule with the first group and the carrier code // combined in the appropriate way. $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule); $numberFormatRule = $firstGroupMatcher->replaceFirst($carrierCodeFormattingRule); $formattedNationalNumber = $m->replaceAll($numberFormatRule); } else { // Use the national prefix formatting rule instead. $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule(); if ($numberFormat == PhoneNumberFormat::NATIONAL && $nationalPrefixFormattingRule !== null && mb_strlen($nationalPrefixFormattingRule) > 0 ) { $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule); $formattedNationalNumber = $m->replaceAll( $firstGroupMatcher->replaceFirst($nationalPrefixFormattingRule) ); } else { $formattedNationalNumber = $m->replaceAll($numberFormatRule); } } if ($numberFormat == PhoneNumberFormat::RFC3966) { // Strip any leading punctuation. $matcher = new Matcher(static::$SEPARATOR_PATTERN, $formattedNationalNumber); if ($matcher->lookingAt()) { $formattedNationalNumber = $matcher->replaceFirst(''); } // Replace the rest with a dash between each number group. $formattedNationalNumber = $matcher->reset($formattedNationalNumber)->replaceAll('-'); } return $formattedNationalNumber; }
[ "public", "function", "formatNsnUsingPattern", "(", "$", "nationalNumber", ",", "NumberFormat", "$", "formattingPattern", ",", "$", "numberFormat", ",", "$", "carrierCode", "=", "null", ")", "{", "$", "numberFormatRule", "=", "$", "formattingPattern", "->", "getFormat", "(", ")", ";", "$", "m", "=", "new", "Matcher", "(", "$", "formattingPattern", "->", "getPattern", "(", ")", ",", "$", "nationalNumber", ")", ";", "if", "(", "$", "numberFormat", "===", "PhoneNumberFormat", "::", "NATIONAL", "&&", "$", "carrierCode", "!==", "null", "&&", "mb_strlen", "(", "$", "carrierCode", ")", ">", "0", "&&", "mb_strlen", "(", "$", "formattingPattern", "->", "getDomesticCarrierCodeFormattingRule", "(", ")", ")", ">", "0", ")", "{", "// Replace the $CC in the formatting rule with the desired carrier code.", "$", "carrierCodeFormattingRule", "=", "$", "formattingPattern", "->", "getDomesticCarrierCodeFormattingRule", "(", ")", ";", "$", "carrierCodeFormattingRule", "=", "str_replace", "(", "static", "::", "CC_STRING", ",", "$", "carrierCode", ",", "$", "carrierCodeFormattingRule", ")", ";", "// Now replace the $FG in the formatting rule with the first group and the carrier code", "// combined in the appropriate way.", "$", "firstGroupMatcher", "=", "new", "Matcher", "(", "static", "::", "FIRST_GROUP_PATTERN", ",", "$", "numberFormatRule", ")", ";", "$", "numberFormatRule", "=", "$", "firstGroupMatcher", "->", "replaceFirst", "(", "$", "carrierCodeFormattingRule", ")", ";", "$", "formattedNationalNumber", "=", "$", "m", "->", "replaceAll", "(", "$", "numberFormatRule", ")", ";", "}", "else", "{", "// Use the national prefix formatting rule instead.", "$", "nationalPrefixFormattingRule", "=", "$", "formattingPattern", "->", "getNationalPrefixFormattingRule", "(", ")", ";", "if", "(", "$", "numberFormat", "==", "PhoneNumberFormat", "::", "NATIONAL", "&&", "$", "nationalPrefixFormattingRule", "!==", "null", "&&", "mb_strlen", "(", "$", "nationalPrefixFormattingRule", ")", ">", "0", ")", "{", "$", "firstGroupMatcher", "=", "new", "Matcher", "(", "static", "::", "FIRST_GROUP_PATTERN", ",", "$", "numberFormatRule", ")", ";", "$", "formattedNationalNumber", "=", "$", "m", "->", "replaceAll", "(", "$", "firstGroupMatcher", "->", "replaceFirst", "(", "$", "nationalPrefixFormattingRule", ")", ")", ";", "}", "else", "{", "$", "formattedNationalNumber", "=", "$", "m", "->", "replaceAll", "(", "$", "numberFormatRule", ")", ";", "}", "}", "if", "(", "$", "numberFormat", "==", "PhoneNumberFormat", "::", "RFC3966", ")", "{", "// Strip any leading punctuation.", "$", "matcher", "=", "new", "Matcher", "(", "static", "::", "$", "SEPARATOR_PATTERN", ",", "$", "formattedNationalNumber", ")", ";", "if", "(", "$", "matcher", "->", "lookingAt", "(", ")", ")", "{", "$", "formattedNationalNumber", "=", "$", "matcher", "->", "replaceFirst", "(", "''", ")", ";", "}", "// Replace the rest with a dash between each number group.", "$", "formattedNationalNumber", "=", "$", "matcher", "->", "reset", "(", "$", "formattedNationalNumber", ")", "->", "replaceAll", "(", "'-'", ")", ";", "}", "return", "$", "formattedNationalNumber", ";", "}" ]
Note that carrierCode is optional - if null or an empty string, no carrier code replacement will take place. @param string $nationalNumber @param NumberFormat $formattingPattern @param int $numberFormat PhoneNumberFormat @param null|string $carrierCode @return string
[ "Note", "that", "carrierCode", "is", "optional", "-", "if", "null", "or", "an", "empty", "string", "no", "carrier", "code", "replacement", "will", "take", "place", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L1293-L1338
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.maybeAppendFormattedExtension
protected function maybeAppendFormattedExtension(PhoneNumber $number, $metadata, $numberFormat, &$formattedNumber) { if ($number->hasExtension() && mb_strlen($number->getExtension()) > 0) { if ($numberFormat === PhoneNumberFormat::RFC3966) { $formattedNumber .= static::RFC3966_EXTN_PREFIX . $number->getExtension(); } elseif (!empty($metadata) && $metadata->hasPreferredExtnPrefix()) { $formattedNumber .= $metadata->getPreferredExtnPrefix() . $number->getExtension(); } else { $formattedNumber .= static::DEFAULT_EXTN_PREFIX . $number->getExtension(); } } }
php
protected function maybeAppendFormattedExtension(PhoneNumber $number, $metadata, $numberFormat, &$formattedNumber) { if ($number->hasExtension() && mb_strlen($number->getExtension()) > 0) { if ($numberFormat === PhoneNumberFormat::RFC3966) { $formattedNumber .= static::RFC3966_EXTN_PREFIX . $number->getExtension(); } elseif (!empty($metadata) && $metadata->hasPreferredExtnPrefix()) { $formattedNumber .= $metadata->getPreferredExtnPrefix() . $number->getExtension(); } else { $formattedNumber .= static::DEFAULT_EXTN_PREFIX . $number->getExtension(); } } }
[ "protected", "function", "maybeAppendFormattedExtension", "(", "PhoneNumber", "$", "number", ",", "$", "metadata", ",", "$", "numberFormat", ",", "&", "$", "formattedNumber", ")", "{", "if", "(", "$", "number", "->", "hasExtension", "(", ")", "&&", "mb_strlen", "(", "$", "number", "->", "getExtension", "(", ")", ")", ">", "0", ")", "{", "if", "(", "$", "numberFormat", "===", "PhoneNumberFormat", "::", "RFC3966", ")", "{", "$", "formattedNumber", ".=", "static", "::", "RFC3966_EXTN_PREFIX", ".", "$", "number", "->", "getExtension", "(", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", "metadata", ")", "&&", "$", "metadata", "->", "hasPreferredExtnPrefix", "(", ")", ")", "{", "$", "formattedNumber", ".=", "$", "metadata", "->", "getPreferredExtnPrefix", "(", ")", ".", "$", "number", "->", "getExtension", "(", ")", ";", "}", "else", "{", "$", "formattedNumber", ".=", "static", "::", "DEFAULT_EXTN_PREFIX", ".", "$", "number", "->", "getExtension", "(", ")", ";", "}", "}", "}" ]
Appends the formatted extension of a phone number to formattedNumber, if the phone number had an extension specified. @param PhoneNumber $number @param PhoneMetadata|null $metadata @param int $numberFormat PhoneNumberFormat @param string $formattedNumber
[ "Appends", "the", "formatted", "extension", "of", "a", "phone", "number", "to", "formattedNumber", "if", "the", "phone", "number", "had", "an", "extension", "specified", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L1349-L1360
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.getCountryMobileToken
public static function getCountryMobileToken($countryCallingCode) { if (count(static::$MOBILE_TOKEN_MAPPINGS) === 0) { static::initMobileTokenMappings(); } if (array_key_exists($countryCallingCode, static::$MOBILE_TOKEN_MAPPINGS)) { return static::$MOBILE_TOKEN_MAPPINGS[$countryCallingCode]; } return ''; }
php
public static function getCountryMobileToken($countryCallingCode) { if (count(static::$MOBILE_TOKEN_MAPPINGS) === 0) { static::initMobileTokenMappings(); } if (array_key_exists($countryCallingCode, static::$MOBILE_TOKEN_MAPPINGS)) { return static::$MOBILE_TOKEN_MAPPINGS[$countryCallingCode]; } return ''; }
[ "public", "static", "function", "getCountryMobileToken", "(", "$", "countryCallingCode", ")", "{", "if", "(", "count", "(", "static", "::", "$", "MOBILE_TOKEN_MAPPINGS", ")", "===", "0", ")", "{", "static", "::", "initMobileTokenMappings", "(", ")", ";", "}", "if", "(", "array_key_exists", "(", "$", "countryCallingCode", ",", "static", "::", "$", "MOBILE_TOKEN_MAPPINGS", ")", ")", "{", "return", "static", "::", "$", "MOBILE_TOKEN_MAPPINGS", "[", "$", "countryCallingCode", "]", ";", "}", "return", "''", ";", "}" ]
Returns the mobile token for the provided country calling code if it has one, otherwise returns an empty string. A mobile token is a number inserted before the area code when dialing a mobile number from that country from abroad. @param int $countryCallingCode the country calling code for which we want the mobile token @return string the mobile token, as a string, for the given country calling code
[ "Returns", "the", "mobile", "token", "for", "the", "provided", "country", "calling", "code", "if", "it", "has", "one", "otherwise", "returns", "an", "empty", "string", ".", "A", "mobile", "token", "is", "a", "number", "inserted", "before", "the", "area", "code", "when", "dialing", "a", "mobile", "number", "from", "that", "country", "from", "abroad", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L1370-L1380
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.isViablePhoneNumber
public static function isViablePhoneNumber($number) { if (static::$VALID_PHONE_NUMBER_PATTERN === null) { static::initValidPhoneNumberPatterns(); } if (mb_strlen($number) < static::MIN_LENGTH_FOR_NSN) { return false; } $validPhoneNumberPattern = static::getValidPhoneNumberPattern(); $m = preg_match($validPhoneNumberPattern, $number); return $m > 0; }
php
public static function isViablePhoneNumber($number) { if (static::$VALID_PHONE_NUMBER_PATTERN === null) { static::initValidPhoneNumberPatterns(); } if (mb_strlen($number) < static::MIN_LENGTH_FOR_NSN) { return false; } $validPhoneNumberPattern = static::getValidPhoneNumberPattern(); $m = preg_match($validPhoneNumberPattern, $number); return $m > 0; }
[ "public", "static", "function", "isViablePhoneNumber", "(", "$", "number", ")", "{", "if", "(", "static", "::", "$", "VALID_PHONE_NUMBER_PATTERN", "===", "null", ")", "{", "static", "::", "initValidPhoneNumberPatterns", "(", ")", ";", "}", "if", "(", "mb_strlen", "(", "$", "number", ")", "<", "static", "::", "MIN_LENGTH_FOR_NSN", ")", "{", "return", "false", ";", "}", "$", "validPhoneNumberPattern", "=", "static", "::", "getValidPhoneNumberPattern", "(", ")", ";", "$", "m", "=", "preg_match", "(", "$", "validPhoneNumberPattern", ",", "$", "number", ")", ";", "return", "$", "m", ">", "0", ";", "}" ]
Checks to see if the string of characters could possibly be a phone number at all. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance - but does assume that leading non-number symbols have been removed, such as by the method extractPossibleNumber. @param string $number to be checked for viability as a phone number @return boolean true if the number could be a phone number of some sort, otherwise false
[ "Checks", "to", "see", "if", "the", "string", "of", "characters", "could", "possibly", "be", "a", "phone", "number", "at", "all", ".", "At", "the", "moment", "checks", "to", "see", "that", "the", "string", "begins", "with", "at", "least", "2", "digits", "ignoring", "any", "punctuation", "commonly", "found", "in", "phone", "numbers", ".", "This", "method", "does", "not", "require", "the", "number", "to", "be", "normalized", "in", "advance", "-", "but", "does", "assume", "that", "leading", "non", "-", "number", "symbols", "have", "been", "removed", "such", "as", "by", "the", "method", "extractPossibleNumber", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L1412-L1426
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.setItalianLeadingZerosForPhoneNumber
public static function setItalianLeadingZerosForPhoneNumber($nationalNumber, PhoneNumber $phoneNumber) { if (strlen($nationalNumber) > 1 && substr($nationalNumber, 0, 1) == '0') { $phoneNumber->setItalianLeadingZero(true); $numberOfLeadingZeros = 1; // Note that if the national number is all "0"s, the last "0" is not counted as a leading // zero. while ($numberOfLeadingZeros < (strlen($nationalNumber) - 1) && substr($nationalNumber, $numberOfLeadingZeros, 1) == '0') { $numberOfLeadingZeros++; } if ($numberOfLeadingZeros != 1) { $phoneNumber->setNumberOfLeadingZeros($numberOfLeadingZeros); } } }
php
public static function setItalianLeadingZerosForPhoneNumber($nationalNumber, PhoneNumber $phoneNumber) { if (strlen($nationalNumber) > 1 && substr($nationalNumber, 0, 1) == '0') { $phoneNumber->setItalianLeadingZero(true); $numberOfLeadingZeros = 1; // Note that if the national number is all "0"s, the last "0" is not counted as a leading // zero. while ($numberOfLeadingZeros < (strlen($nationalNumber) - 1) && substr($nationalNumber, $numberOfLeadingZeros, 1) == '0') { $numberOfLeadingZeros++; } if ($numberOfLeadingZeros != 1) { $phoneNumber->setNumberOfLeadingZeros($numberOfLeadingZeros); } } }
[ "public", "static", "function", "setItalianLeadingZerosForPhoneNumber", "(", "$", "nationalNumber", ",", "PhoneNumber", "$", "phoneNumber", ")", "{", "if", "(", "strlen", "(", "$", "nationalNumber", ")", ">", "1", "&&", "substr", "(", "$", "nationalNumber", ",", "0", ",", "1", ")", "==", "'0'", ")", "{", "$", "phoneNumber", "->", "setItalianLeadingZero", "(", "true", ")", ";", "$", "numberOfLeadingZeros", "=", "1", ";", "// Note that if the national number is all \"0\"s, the last \"0\" is not counted as a leading", "// zero.", "while", "(", "$", "numberOfLeadingZeros", "<", "(", "strlen", "(", "$", "nationalNumber", ")", "-", "1", ")", "&&", "substr", "(", "$", "nationalNumber", ",", "$", "numberOfLeadingZeros", ",", "1", ")", "==", "'0'", ")", "{", "$", "numberOfLeadingZeros", "++", ";", "}", "if", "(", "$", "numberOfLeadingZeros", "!=", "1", ")", "{", "$", "phoneNumber", "->", "setNumberOfLeadingZeros", "(", "$", "numberOfLeadingZeros", ")", ";", "}", "}", "}" ]
A helper function to set the values related to leading zeros in a PhoneNumber. @param string $nationalNumber @param PhoneNumber $phoneNumber
[ "A", "helper", "function", "to", "set", "the", "values", "related", "to", "leading", "zeros", "in", "a", "PhoneNumber", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L1525-L1541
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.buildNationalNumberForParsing
protected function buildNationalNumberForParsing($numberToParse, &$nationalNumber) { $indexOfPhoneContext = strpos($numberToParse, static::RFC3966_PHONE_CONTEXT); if ($indexOfPhoneContext !== false) { $phoneContextStart = $indexOfPhoneContext + mb_strlen(static::RFC3966_PHONE_CONTEXT); // If the phone context contains a phone number prefix, we need to capture it, whereas domains // will be ignored. if ($phoneContextStart < (strlen($numberToParse) - 1) && substr($numberToParse, $phoneContextStart, 1) == static::PLUS_SIGN) { // Additional parameters might follow the phone context. If so, we will remove them here // because the parameters after phone context are not important for parsing the // phone number. $phoneContextEnd = strpos($numberToParse, ';', $phoneContextStart); if ($phoneContextEnd > 0) { $nationalNumber .= substr($numberToParse, $phoneContextStart, $phoneContextEnd - $phoneContextStart); } else { $nationalNumber .= substr($numberToParse, $phoneContextStart); } } // Now append everything between the "tel:" prefix and the phone-context. This should include // the national number, an optional extension or isdn-subaddress component. Note we also // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs. // In that case, we append everything from the beginning. $indexOfRfc3966Prefix = strpos($numberToParse, static::RFC3966_PREFIX); $indexOfNationalNumber = ($indexOfRfc3966Prefix !== false) ? $indexOfRfc3966Prefix + strlen(static::RFC3966_PREFIX) : 0; $nationalNumber .= substr($numberToParse, $indexOfNationalNumber, $indexOfPhoneContext - $indexOfNationalNumber); } else { // Extract a possible number from the string passed in (this strips leading characters that // could not be the start of a phone number.) $nationalNumber .= static::extractPossibleNumber($numberToParse); } // Delete the isdn-subaddress and everything after it if it is present. Note extension won't // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec, $indexOfIsdn = strpos($nationalNumber, static::RFC3966_ISDN_SUBADDRESS); if ($indexOfIsdn > 0) { $nationalNumber = substr($nationalNumber, 0, $indexOfIsdn); } // If both phone context and isdn-subaddress are absent but other parameters are present, the // parameters are left in nationalNumber. This is because we are concerned about deleting // content from a potential number string when there is no strong evidence that the number is // actually written in RFC3966. }
php
protected function buildNationalNumberForParsing($numberToParse, &$nationalNumber) { $indexOfPhoneContext = strpos($numberToParse, static::RFC3966_PHONE_CONTEXT); if ($indexOfPhoneContext !== false) { $phoneContextStart = $indexOfPhoneContext + mb_strlen(static::RFC3966_PHONE_CONTEXT); // If the phone context contains a phone number prefix, we need to capture it, whereas domains // will be ignored. if ($phoneContextStart < (strlen($numberToParse) - 1) && substr($numberToParse, $phoneContextStart, 1) == static::PLUS_SIGN) { // Additional parameters might follow the phone context. If so, we will remove them here // because the parameters after phone context are not important for parsing the // phone number. $phoneContextEnd = strpos($numberToParse, ';', $phoneContextStart); if ($phoneContextEnd > 0) { $nationalNumber .= substr($numberToParse, $phoneContextStart, $phoneContextEnd - $phoneContextStart); } else { $nationalNumber .= substr($numberToParse, $phoneContextStart); } } // Now append everything between the "tel:" prefix and the phone-context. This should include // the national number, an optional extension or isdn-subaddress component. Note we also // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs. // In that case, we append everything from the beginning. $indexOfRfc3966Prefix = strpos($numberToParse, static::RFC3966_PREFIX); $indexOfNationalNumber = ($indexOfRfc3966Prefix !== false) ? $indexOfRfc3966Prefix + strlen(static::RFC3966_PREFIX) : 0; $nationalNumber .= substr($numberToParse, $indexOfNationalNumber, $indexOfPhoneContext - $indexOfNationalNumber); } else { // Extract a possible number from the string passed in (this strips leading characters that // could not be the start of a phone number.) $nationalNumber .= static::extractPossibleNumber($numberToParse); } // Delete the isdn-subaddress and everything after it if it is present. Note extension won't // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec, $indexOfIsdn = strpos($nationalNumber, static::RFC3966_ISDN_SUBADDRESS); if ($indexOfIsdn > 0) { $nationalNumber = substr($nationalNumber, 0, $indexOfIsdn); } // If both phone context and isdn-subaddress are absent but other parameters are present, the // parameters are left in nationalNumber. This is because we are concerned about deleting // content from a potential number string when there is no strong evidence that the number is // actually written in RFC3966. }
[ "protected", "function", "buildNationalNumberForParsing", "(", "$", "numberToParse", ",", "&", "$", "nationalNumber", ")", "{", "$", "indexOfPhoneContext", "=", "strpos", "(", "$", "numberToParse", ",", "static", "::", "RFC3966_PHONE_CONTEXT", ")", ";", "if", "(", "$", "indexOfPhoneContext", "!==", "false", ")", "{", "$", "phoneContextStart", "=", "$", "indexOfPhoneContext", "+", "mb_strlen", "(", "static", "::", "RFC3966_PHONE_CONTEXT", ")", ";", "// If the phone context contains a phone number prefix, we need to capture it, whereas domains", "// will be ignored.", "if", "(", "$", "phoneContextStart", "<", "(", "strlen", "(", "$", "numberToParse", ")", "-", "1", ")", "&&", "substr", "(", "$", "numberToParse", ",", "$", "phoneContextStart", ",", "1", ")", "==", "static", "::", "PLUS_SIGN", ")", "{", "// Additional parameters might follow the phone context. If so, we will remove them here", "// because the parameters after phone context are not important for parsing the", "// phone number.", "$", "phoneContextEnd", "=", "strpos", "(", "$", "numberToParse", ",", "';'", ",", "$", "phoneContextStart", ")", ";", "if", "(", "$", "phoneContextEnd", ">", "0", ")", "{", "$", "nationalNumber", ".=", "substr", "(", "$", "numberToParse", ",", "$", "phoneContextStart", ",", "$", "phoneContextEnd", "-", "$", "phoneContextStart", ")", ";", "}", "else", "{", "$", "nationalNumber", ".=", "substr", "(", "$", "numberToParse", ",", "$", "phoneContextStart", ")", ";", "}", "}", "// Now append everything between the \"tel:\" prefix and the phone-context. This should include", "// the national number, an optional extension or isdn-subaddress component. Note we also", "// handle the case when \"tel:\" is missing, as we have seen in some of the phone number inputs.", "// In that case, we append everything from the beginning.", "$", "indexOfRfc3966Prefix", "=", "strpos", "(", "$", "numberToParse", ",", "static", "::", "RFC3966_PREFIX", ")", ";", "$", "indexOfNationalNumber", "=", "(", "$", "indexOfRfc3966Prefix", "!==", "false", ")", "?", "$", "indexOfRfc3966Prefix", "+", "strlen", "(", "static", "::", "RFC3966_PREFIX", ")", ":", "0", ";", "$", "nationalNumber", ".=", "substr", "(", "$", "numberToParse", ",", "$", "indexOfNationalNumber", ",", "$", "indexOfPhoneContext", "-", "$", "indexOfNationalNumber", ")", ";", "}", "else", "{", "// Extract a possible number from the string passed in (this strips leading characters that", "// could not be the start of a phone number.)", "$", "nationalNumber", ".=", "static", "::", "extractPossibleNumber", "(", "$", "numberToParse", ")", ";", "}", "// Delete the isdn-subaddress and everything after it if it is present. Note extension won't", "// appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,", "$", "indexOfIsdn", "=", "strpos", "(", "$", "nationalNumber", ",", "static", "::", "RFC3966_ISDN_SUBADDRESS", ")", ";", "if", "(", "$", "indexOfIsdn", ">", "0", ")", "{", "$", "nationalNumber", "=", "substr", "(", "$", "nationalNumber", ",", "0", ",", "$", "indexOfIsdn", ")", ";", "}", "// If both phone context and isdn-subaddress are absent but other parameters are present, the", "// parameters are left in nationalNumber. This is because we are concerned about deleting", "// content from a potential number string when there is no strong evidence that the number is", "// actually written in RFC3966.", "}" ]
Converts numberToParse to a form that we can parse and write it to nationalNumber if it is written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber. @param string $numberToParse @param string $nationalNumber
[ "Converts", "numberToParse", "to", "a", "form", "that", "we", "can", "parse", "and", "write", "it", "to", "nationalNumber", "if", "it", "is", "written", "in", "RFC3966", ";", "otherwise", "extract", "a", "possible", "number", "out", "of", "it", "and", "write", "to", "nationalNumber", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L1738-L1783
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.checkRegionForParsing
protected function checkRegionForParsing($numberToParse, $defaultRegion) { if (!$this->isValidRegionCode($defaultRegion)) { // If the number is null or empty, we can't infer the region. $plusCharsPatternMatcher = new Matcher(static::$PLUS_CHARS_PATTERN, $numberToParse); if ($numberToParse === null || mb_strlen($numberToParse) == 0 || !$plusCharsPatternMatcher->lookingAt()) { return false; } } return true; }
php
protected function checkRegionForParsing($numberToParse, $defaultRegion) { if (!$this->isValidRegionCode($defaultRegion)) { // If the number is null or empty, we can't infer the region. $plusCharsPatternMatcher = new Matcher(static::$PLUS_CHARS_PATTERN, $numberToParse); if ($numberToParse === null || mb_strlen($numberToParse) == 0 || !$plusCharsPatternMatcher->lookingAt()) { return false; } } return true; }
[ "protected", "function", "checkRegionForParsing", "(", "$", "numberToParse", ",", "$", "defaultRegion", ")", "{", "if", "(", "!", "$", "this", "->", "isValidRegionCode", "(", "$", "defaultRegion", ")", ")", "{", "// If the number is null or empty, we can't infer the region.", "$", "plusCharsPatternMatcher", "=", "new", "Matcher", "(", "static", "::", "$", "PLUS_CHARS_PATTERN", ",", "$", "numberToParse", ")", ";", "if", "(", "$", "numberToParse", "===", "null", "||", "mb_strlen", "(", "$", "numberToParse", ")", "==", "0", "||", "!", "$", "plusCharsPatternMatcher", "->", "lookingAt", "(", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks to see that the region code used is valid, or if it is not valid, that the number to parse starts with a + symbol so that we can attempt to infer the region from the number. Returns false if it cannot use the region provided and the region cannot be inferred. @param string $numberToParse @param string $defaultRegion @return bool
[ "Checks", "to", "see", "that", "the", "region", "code", "used", "is", "valid", "or", "if", "it", "is", "not", "valid", "that", "the", "number", "to", "parse", "starts", "with", "a", "+", "symbol", "so", "that", "we", "can", "attempt", "to", "infer", "the", "region", "from", "the", "number", ".", "Returns", "false", "if", "it", "cannot", "use", "the", "region", "provided", "and", "the", "region", "cannot", "be", "inferred", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L1836-L1846
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.parsePrefixAsIdd
protected function parsePrefixAsIdd($iddPattern, &$number) { $m = new Matcher($iddPattern, $number); if ($m->lookingAt()) { $matchEnd = $m->end(); // Only strip this if the first digit after the match is not a 0, since country calling codes // cannot begin with 0. $digitMatcher = new Matcher(static::$CAPTURING_DIGIT_PATTERN, substr($number, $matchEnd)); if ($digitMatcher->find()) { $normalizedGroup = static::normalizeDigitsOnly($digitMatcher->group(1)); if ($normalizedGroup == '0') { return false; } } $number = substr($number, $matchEnd); return true; } return false; }
php
protected function parsePrefixAsIdd($iddPattern, &$number) { $m = new Matcher($iddPattern, $number); if ($m->lookingAt()) { $matchEnd = $m->end(); // Only strip this if the first digit after the match is not a 0, since country calling codes // cannot begin with 0. $digitMatcher = new Matcher(static::$CAPTURING_DIGIT_PATTERN, substr($number, $matchEnd)); if ($digitMatcher->find()) { $normalizedGroup = static::normalizeDigitsOnly($digitMatcher->group(1)); if ($normalizedGroup == '0') { return false; } } $number = substr($number, $matchEnd); return true; } return false; }
[ "protected", "function", "parsePrefixAsIdd", "(", "$", "iddPattern", ",", "&", "$", "number", ")", "{", "$", "m", "=", "new", "Matcher", "(", "$", "iddPattern", ",", "$", "number", ")", ";", "if", "(", "$", "m", "->", "lookingAt", "(", ")", ")", "{", "$", "matchEnd", "=", "$", "m", "->", "end", "(", ")", ";", "// Only strip this if the first digit after the match is not a 0, since country calling codes", "// cannot begin with 0.", "$", "digitMatcher", "=", "new", "Matcher", "(", "static", "::", "$", "CAPTURING_DIGIT_PATTERN", ",", "substr", "(", "$", "number", ",", "$", "matchEnd", ")", ")", ";", "if", "(", "$", "digitMatcher", "->", "find", "(", ")", ")", "{", "$", "normalizedGroup", "=", "static", "::", "normalizeDigitsOnly", "(", "$", "digitMatcher", "->", "group", "(", "1", ")", ")", ";", "if", "(", "$", "normalizedGroup", "==", "'0'", ")", "{", "return", "false", ";", "}", "}", "$", "number", "=", "substr", "(", "$", "number", ",", "$", "matchEnd", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Strips the IDD from the start of the number if present. Helper function used by maybeStripInternationalPrefixAndNormalize. @param string $iddPattern @param string $number @return bool
[ "Strips", "the", "IDD", "from", "the", "start", "of", "the", "number", "if", "present", ".", "Helper", "function", "used", "by", "maybeStripInternationalPrefixAndNormalize", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L2067-L2085
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.extractCountryCode
public function extractCountryCode($fullNumber, &$nationalNumber) { if ((mb_strlen($fullNumber) == 0) || ($fullNumber[0] == '0')) { // Country codes do not begin with a '0'. return 0; } $numberLength = mb_strlen($fullNumber); for ($i = 1; $i <= static::MAX_LENGTH_COUNTRY_CODE && $i <= $numberLength; $i++) { $potentialCountryCode = (int)substr($fullNumber, 0, $i); if (isset($this->countryCallingCodeToRegionCodeMap[$potentialCountryCode])) { $nationalNumber .= substr($fullNumber, $i); return $potentialCountryCode; } } return 0; }
php
public function extractCountryCode($fullNumber, &$nationalNumber) { if ((mb_strlen($fullNumber) == 0) || ($fullNumber[0] == '0')) { // Country codes do not begin with a '0'. return 0; } $numberLength = mb_strlen($fullNumber); for ($i = 1; $i <= static::MAX_LENGTH_COUNTRY_CODE && $i <= $numberLength; $i++) { $potentialCountryCode = (int)substr($fullNumber, 0, $i); if (isset($this->countryCallingCodeToRegionCodeMap[$potentialCountryCode])) { $nationalNumber .= substr($fullNumber, $i); return $potentialCountryCode; } } return 0; }
[ "public", "function", "extractCountryCode", "(", "$", "fullNumber", ",", "&", "$", "nationalNumber", ")", "{", "if", "(", "(", "mb_strlen", "(", "$", "fullNumber", ")", "==", "0", ")", "||", "(", "$", "fullNumber", "[", "0", "]", "==", "'0'", ")", ")", "{", "// Country codes do not begin with a '0'.", "return", "0", ";", "}", "$", "numberLength", "=", "mb_strlen", "(", "$", "fullNumber", ")", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<=", "static", "::", "MAX_LENGTH_COUNTRY_CODE", "&&", "$", "i", "<=", "$", "numberLength", ";", "$", "i", "++", ")", "{", "$", "potentialCountryCode", "=", "(", "int", ")", "substr", "(", "$", "fullNumber", ",", "0", ",", "$", "i", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "countryCallingCodeToRegionCodeMap", "[", "$", "potentialCountryCode", "]", ")", ")", "{", "$", "nationalNumber", ".=", "substr", "(", "$", "fullNumber", ",", "$", "i", ")", ";", "return", "$", "potentialCountryCode", ";", "}", "}", "return", "0", ";", "}" ]
Extracts country calling code from fullNumber, returns it and places the remaining number in nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber unmodified. @param string $fullNumber @param string $nationalNumber @return int @internal
[ "Extracts", "country", "calling", "code", "from", "fullNumber", "returns", "it", "and", "places", "the", "remaining", "number", "in", "nationalNumber", ".", "It", "assumes", "that", "the", "leading", "plus", "sign", "or", "IDD", "has", "already", "been", "removed", ".", "Returns", "0", "if", "fullNumber", "doesn", "t", "start", "with", "a", "valid", "country", "calling", "code", "and", "leaves", "nationalNumber", "unmodified", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L2096-L2111
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.getRegionCodesForCountryCode
public function getRegionCodesForCountryCode($countryCallingCode) { $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null; return $regionCodes === null ? array() : $regionCodes; }
php
public function getRegionCodesForCountryCode($countryCallingCode) { $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null; return $regionCodes === null ? array() : $regionCodes; }
[ "public", "function", "getRegionCodesForCountryCode", "(", "$", "countryCallingCode", ")", "{", "$", "regionCodes", "=", "isset", "(", "$", "this", "->", "countryCallingCodeToRegionCodeMap", "[", "$", "countryCallingCode", "]", ")", "?", "$", "this", "->", "countryCallingCodeToRegionCodeMap", "[", "$", "countryCallingCode", "]", ":", "null", ";", "return", "$", "regionCodes", "===", "null", "?", "array", "(", ")", ":", "$", "regionCodes", ";", "}" ]
Returns a list with the region codes that match the specific country calling code. For non-geographical country calling codes, the region code 001 is returned. Also, in the case of no region code being found, an empty list is returned. @param int $countryCallingCode @return array
[ "Returns", "a", "list", "with", "the", "region", "codes", "that", "match", "the", "specific", "country", "calling", "code", ".", "For", "non", "-", "geographical", "country", "calling", "codes", "the", "region", "code", "001", "is", "returned", ".", "Also", "in", "the", "case", "of", "no", "region", "code", "being", "found", "an", "empty", "list", "is", "returned", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L2293-L2297
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.getCountryCodeForValidRegion
protected function getCountryCodeForValidRegion($regionCode) { $metadata = $this->getMetadataForRegion($regionCode); if ($metadata === null) { throw new \InvalidArgumentException('Invalid region code: ' . $regionCode); } return $metadata->getCountryCode(); }
php
protected function getCountryCodeForValidRegion($regionCode) { $metadata = $this->getMetadataForRegion($regionCode); if ($metadata === null) { throw new \InvalidArgumentException('Invalid region code: ' . $regionCode); } return $metadata->getCountryCode(); }
[ "protected", "function", "getCountryCodeForValidRegion", "(", "$", "regionCode", ")", "{", "$", "metadata", "=", "$", "this", "->", "getMetadataForRegion", "(", "$", "regionCode", ")", ";", "if", "(", "$", "metadata", "===", "null", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid region code: '", ".", "$", "regionCode", ")", ";", "}", "return", "$", "metadata", "->", "getCountryCode", "(", ")", ";", "}" ]
Returns the country calling code for a specific region. For example, this would be 1 for the United States, and 64 for New Zealand. Assumes the region is already valid. @param string $regionCode the region that we want to get the country calling code for @return int the country calling code for the region denoted by regionCode @throws \InvalidArgumentException if the region is invalid
[ "Returns", "the", "country", "calling", "code", "for", "a", "specific", "region", ".", "For", "example", "this", "would", "be", "1", "for", "the", "United", "States", "and", "64", "for", "New", "Zealand", ".", "Assumes", "the", "region", "is", "already", "valid", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L2322-L2329
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.formatOutOfCountryKeepingAlphaChars
public function formatOutOfCountryKeepingAlphaChars(PhoneNumber $number, $regionCallingFrom) { $rawInput = $number->getRawInput(); // If there is no raw input, then we can't keep alpha characters because there aren't any. // In this case, we return formatOutOfCountryCallingNumber. if (mb_strlen($rawInput) == 0) { return $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom); } $countryCode = $number->getCountryCode(); if (!$this->hasValidCountryCallingCode($countryCode)) { return $rawInput; } // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing // the number in raw_input with the parsed number. // To do this, first we normalize punctuation. We retain number grouping symbols such as " " // only. $rawInput = self::normalizeHelper($rawInput, static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true); // Now we trim everything before the first three digits in the parsed number. We choose three // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't // trim anything at all. Similarly, if the national number was less than three digits, we don't // trim anything at all. $nationalNumber = $this->getNationalSignificantNumber($number); if (mb_strlen($nationalNumber) > 3) { $firstNationalNumberDigit = strpos($rawInput, substr($nationalNumber, 0, 3)); if ($firstNationalNumberDigit !== false) { $rawInput = substr($rawInput, $firstNationalNumberDigit); } } $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom); if ($countryCode == static::NANPA_COUNTRY_CODE) { if ($this->isNANPACountry($regionCallingFrom)) { return $countryCode . ' ' . $rawInput; } } elseif ($metadataForRegionCallingFrom !== null && $countryCode == $this->getCountryCodeForValidRegion($regionCallingFrom) ) { $formattingPattern = $this->chooseFormattingPatternForNumber( $metadataForRegionCallingFrom->numberFormats(), $nationalNumber ); if ($formattingPattern === null) { // If no pattern above is matched, we format the original input. return $rawInput; } $newFormat = new NumberFormat(); $newFormat->mergeFrom($formattingPattern); // The first group is the first group of digits that the user wrote together. $newFormat->setPattern("(\\d+)(.*)"); // Here we just concatenate them back together after the national prefix has been fixed. $newFormat->setFormat('$1$2'); // Now we format using this pattern instead of the default pattern, but with the national // prefix prefixed if necessary. // This will not work in the cases where the pattern (and not the leading digits) decide // whether a national prefix needs to be used, since we have overridden the pattern to match // anything, but that is not the case in the metadata to date. return $this->formatNsnUsingPattern($rawInput, $newFormat, PhoneNumberFormat::NATIONAL); } $internationalPrefixForFormatting = ''; // If an unsupported region-calling-from is entered, or a country with multiple international // prefixes, the international format of the number is returned, unless there is a preferred // international prefix. if ($metadataForRegionCallingFrom !== null) { $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix(); $uniqueInternationalPrefixMatcher = new Matcher(static::SINGLE_INTERNATIONAL_PREFIX, $internationalPrefix); $internationalPrefixForFormatting = $uniqueInternationalPrefixMatcher->matches() ? $internationalPrefix : $metadataForRegionCallingFrom->getPreferredInternationalPrefix(); } $formattedNumber = $rawInput; $regionCode = $this->getRegionCodeForCountryCode($countryCode); // Metadata cannot be null because the country calling code is valid. $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode); $this->maybeAppendFormattedExtension( $number, $metadataForRegion, PhoneNumberFormat::INTERNATIONAL, $formattedNumber ); if (mb_strlen($internationalPrefixForFormatting) > 0) { $formattedNumber = $internationalPrefixForFormatting . ' ' . $countryCode . ' ' . $formattedNumber; } else { // Invalid region entered as country-calling-from (so no metadata was found for it) or the // region chosen has multiple international dialling prefixes. $this->prefixNumberWithCountryCallingCode( $countryCode, PhoneNumberFormat::INTERNATIONAL, $formattedNumber ); } return $formattedNumber; }
php
public function formatOutOfCountryKeepingAlphaChars(PhoneNumber $number, $regionCallingFrom) { $rawInput = $number->getRawInput(); // If there is no raw input, then we can't keep alpha characters because there aren't any. // In this case, we return formatOutOfCountryCallingNumber. if (mb_strlen($rawInput) == 0) { return $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom); } $countryCode = $number->getCountryCode(); if (!$this->hasValidCountryCallingCode($countryCode)) { return $rawInput; } // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing // the number in raw_input with the parsed number. // To do this, first we normalize punctuation. We retain number grouping symbols such as " " // only. $rawInput = self::normalizeHelper($rawInput, static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true); // Now we trim everything before the first three digits in the parsed number. We choose three // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't // trim anything at all. Similarly, if the national number was less than three digits, we don't // trim anything at all. $nationalNumber = $this->getNationalSignificantNumber($number); if (mb_strlen($nationalNumber) > 3) { $firstNationalNumberDigit = strpos($rawInput, substr($nationalNumber, 0, 3)); if ($firstNationalNumberDigit !== false) { $rawInput = substr($rawInput, $firstNationalNumberDigit); } } $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom); if ($countryCode == static::NANPA_COUNTRY_CODE) { if ($this->isNANPACountry($regionCallingFrom)) { return $countryCode . ' ' . $rawInput; } } elseif ($metadataForRegionCallingFrom !== null && $countryCode == $this->getCountryCodeForValidRegion($regionCallingFrom) ) { $formattingPattern = $this->chooseFormattingPatternForNumber( $metadataForRegionCallingFrom->numberFormats(), $nationalNumber ); if ($formattingPattern === null) { // If no pattern above is matched, we format the original input. return $rawInput; } $newFormat = new NumberFormat(); $newFormat->mergeFrom($formattingPattern); // The first group is the first group of digits that the user wrote together. $newFormat->setPattern("(\\d+)(.*)"); // Here we just concatenate them back together after the national prefix has been fixed. $newFormat->setFormat('$1$2'); // Now we format using this pattern instead of the default pattern, but with the national // prefix prefixed if necessary. // This will not work in the cases where the pattern (and not the leading digits) decide // whether a national prefix needs to be used, since we have overridden the pattern to match // anything, but that is not the case in the metadata to date. return $this->formatNsnUsingPattern($rawInput, $newFormat, PhoneNumberFormat::NATIONAL); } $internationalPrefixForFormatting = ''; // If an unsupported region-calling-from is entered, or a country with multiple international // prefixes, the international format of the number is returned, unless there is a preferred // international prefix. if ($metadataForRegionCallingFrom !== null) { $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix(); $uniqueInternationalPrefixMatcher = new Matcher(static::SINGLE_INTERNATIONAL_PREFIX, $internationalPrefix); $internationalPrefixForFormatting = $uniqueInternationalPrefixMatcher->matches() ? $internationalPrefix : $metadataForRegionCallingFrom->getPreferredInternationalPrefix(); } $formattedNumber = $rawInput; $regionCode = $this->getRegionCodeForCountryCode($countryCode); // Metadata cannot be null because the country calling code is valid. $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode); $this->maybeAppendFormattedExtension( $number, $metadataForRegion, PhoneNumberFormat::INTERNATIONAL, $formattedNumber ); if (mb_strlen($internationalPrefixForFormatting) > 0) { $formattedNumber = $internationalPrefixForFormatting . ' ' . $countryCode . ' ' . $formattedNumber; } else { // Invalid region entered as country-calling-from (so no metadata was found for it) or the // region chosen has multiple international dialling prefixes. $this->prefixNumberWithCountryCallingCode( $countryCode, PhoneNumberFormat::INTERNATIONAL, $formattedNumber ); } return $formattedNumber; }
[ "public", "function", "formatOutOfCountryKeepingAlphaChars", "(", "PhoneNumber", "$", "number", ",", "$", "regionCallingFrom", ")", "{", "$", "rawInput", "=", "$", "number", "->", "getRawInput", "(", ")", ";", "// If there is no raw input, then we can't keep alpha characters because there aren't any.", "// In this case, we return formatOutOfCountryCallingNumber.", "if", "(", "mb_strlen", "(", "$", "rawInput", ")", "==", "0", ")", "{", "return", "$", "this", "->", "formatOutOfCountryCallingNumber", "(", "$", "number", ",", "$", "regionCallingFrom", ")", ";", "}", "$", "countryCode", "=", "$", "number", "->", "getCountryCode", "(", ")", ";", "if", "(", "!", "$", "this", "->", "hasValidCountryCallingCode", "(", "$", "countryCode", ")", ")", "{", "return", "$", "rawInput", ";", "}", "// Strip any prefix such as country calling code, IDD, that was present. We do this by comparing", "// the number in raw_input with the parsed number.", "// To do this, first we normalize punctuation. We retain number grouping symbols such as \" \"", "// only.", "$", "rawInput", "=", "self", "::", "normalizeHelper", "(", "$", "rawInput", ",", "static", "::", "$", "ALL_PLUS_NUMBER_GROUPING_SYMBOLS", ",", "true", ")", ";", "// Now we trim everything before the first three digits in the parsed number. We choose three", "// because all valid alpha numbers have 3 digits at the start - if it does not, then we don't", "// trim anything at all. Similarly, if the national number was less than three digits, we don't", "// trim anything at all.", "$", "nationalNumber", "=", "$", "this", "->", "getNationalSignificantNumber", "(", "$", "number", ")", ";", "if", "(", "mb_strlen", "(", "$", "nationalNumber", ")", ">", "3", ")", "{", "$", "firstNationalNumberDigit", "=", "strpos", "(", "$", "rawInput", ",", "substr", "(", "$", "nationalNumber", ",", "0", ",", "3", ")", ")", ";", "if", "(", "$", "firstNationalNumberDigit", "!==", "false", ")", "{", "$", "rawInput", "=", "substr", "(", "$", "rawInput", ",", "$", "firstNationalNumberDigit", ")", ";", "}", "}", "$", "metadataForRegionCallingFrom", "=", "$", "this", "->", "getMetadataForRegion", "(", "$", "regionCallingFrom", ")", ";", "if", "(", "$", "countryCode", "==", "static", "::", "NANPA_COUNTRY_CODE", ")", "{", "if", "(", "$", "this", "->", "isNANPACountry", "(", "$", "regionCallingFrom", ")", ")", "{", "return", "$", "countryCode", ".", "' '", ".", "$", "rawInput", ";", "}", "}", "elseif", "(", "$", "metadataForRegionCallingFrom", "!==", "null", "&&", "$", "countryCode", "==", "$", "this", "->", "getCountryCodeForValidRegion", "(", "$", "regionCallingFrom", ")", ")", "{", "$", "formattingPattern", "=", "$", "this", "->", "chooseFormattingPatternForNumber", "(", "$", "metadataForRegionCallingFrom", "->", "numberFormats", "(", ")", ",", "$", "nationalNumber", ")", ";", "if", "(", "$", "formattingPattern", "===", "null", ")", "{", "// If no pattern above is matched, we format the original input.", "return", "$", "rawInput", ";", "}", "$", "newFormat", "=", "new", "NumberFormat", "(", ")", ";", "$", "newFormat", "->", "mergeFrom", "(", "$", "formattingPattern", ")", ";", "// The first group is the first group of digits that the user wrote together.", "$", "newFormat", "->", "setPattern", "(", "\"(\\\\d+)(.*)\"", ")", ";", "// Here we just concatenate them back together after the national prefix has been fixed.", "$", "newFormat", "->", "setFormat", "(", "'$1$2'", ")", ";", "// Now we format using this pattern instead of the default pattern, but with the national", "// prefix prefixed if necessary.", "// This will not work in the cases where the pattern (and not the leading digits) decide", "// whether a national prefix needs to be used, since we have overridden the pattern to match", "// anything, but that is not the case in the metadata to date.", "return", "$", "this", "->", "formatNsnUsingPattern", "(", "$", "rawInput", ",", "$", "newFormat", ",", "PhoneNumberFormat", "::", "NATIONAL", ")", ";", "}", "$", "internationalPrefixForFormatting", "=", "''", ";", "// If an unsupported region-calling-from is entered, or a country with multiple international", "// prefixes, the international format of the number is returned, unless there is a preferred", "// international prefix.", "if", "(", "$", "metadataForRegionCallingFrom", "!==", "null", ")", "{", "$", "internationalPrefix", "=", "$", "metadataForRegionCallingFrom", "->", "getInternationalPrefix", "(", ")", ";", "$", "uniqueInternationalPrefixMatcher", "=", "new", "Matcher", "(", "static", "::", "SINGLE_INTERNATIONAL_PREFIX", ",", "$", "internationalPrefix", ")", ";", "$", "internationalPrefixForFormatting", "=", "$", "uniqueInternationalPrefixMatcher", "->", "matches", "(", ")", "?", "$", "internationalPrefix", ":", "$", "metadataForRegionCallingFrom", "->", "getPreferredInternationalPrefix", "(", ")", ";", "}", "$", "formattedNumber", "=", "$", "rawInput", ";", "$", "regionCode", "=", "$", "this", "->", "getRegionCodeForCountryCode", "(", "$", "countryCode", ")", ";", "// Metadata cannot be null because the country calling code is valid.", "$", "metadataForRegion", "=", "$", "this", "->", "getMetadataForRegionOrCallingCode", "(", "$", "countryCode", ",", "$", "regionCode", ")", ";", "$", "this", "->", "maybeAppendFormattedExtension", "(", "$", "number", ",", "$", "metadataForRegion", ",", "PhoneNumberFormat", "::", "INTERNATIONAL", ",", "$", "formattedNumber", ")", ";", "if", "(", "mb_strlen", "(", "$", "internationalPrefixForFormatting", ")", ">", "0", ")", "{", "$", "formattedNumber", "=", "$", "internationalPrefixForFormatting", ".", "' '", ".", "$", "countryCode", ".", "' '", ".", "$", "formattedNumber", ";", "}", "else", "{", "// Invalid region entered as country-calling-from (so no metadata was found for it) or the", "// region chosen has multiple international dialling prefixes.", "$", "this", "->", "prefixNumberWithCountryCallingCode", "(", "$", "countryCode", ",", "PhoneNumberFormat", "::", "INTERNATIONAL", ",", "$", "formattedNumber", ")", ";", "}", "return", "$", "formattedNumber", ";", "}" ]
Formats a phone number for out-of-country dialing purposes. Note that in this version, if the number was entered originally using alpha characters and this version of the number is stored in raw_input, this representation of the number will be used rather than the digit representation. Grouping information, as specified by characters such as "-" and " ", will be retained. <p><b>Caveats:</b></p> <ul> <li> This will not produce good results if the country calling code is both present in the raw input _and_ is the start of the national number. This is not a problem in the regions which typically use alpha numbers. <li> This will also not produce good results if the raw input has any grouping information within the first three digits of the national number, and if the function needs to strip preceding digits/words in the raw input before these digits. Normally people group the first three digits together so this is not a huge problem - and will be fixed if it proves to be so. </ul> @param PhoneNumber $number the phone number that needs to be formatted @param String $regionCallingFrom the region where the call is being placed @return String the formatted phone number
[ "Formats", "a", "phone", "number", "for", "out", "-", "of", "-", "country", "dialing", "purposes", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L2559-L2651
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.formatOutOfCountryCallingNumber
public function formatOutOfCountryCallingNumber(PhoneNumber $number, $regionCallingFrom) { if (!$this->isValidRegionCode($regionCallingFrom)) { return $this->format($number, PhoneNumberFormat::INTERNATIONAL); } $countryCallingCode = $number->getCountryCode(); $nationalSignificantNumber = $this->getNationalSignificantNumber($number); if (!$this->hasValidCountryCallingCode($countryCallingCode)) { return $nationalSignificantNumber; } if ($countryCallingCode == static::NANPA_COUNTRY_CODE) { if ($this->isNANPACountry($regionCallingFrom)) { // For NANPA regions, return the national format for these regions but prefix it with the // country calling code. return $countryCallingCode . ' ' . $this->format($number, PhoneNumberFormat::NATIONAL); } } elseif ($countryCallingCode == $this->getCountryCodeForValidRegion($regionCallingFrom)) { // If regions share a country calling code, the country calling code need not be dialled. // This also applies when dialling within a region, so this if clause covers both these cases. // Technically this is the case for dialling from La Reunion to other overseas departments of // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this // edge case for now and for those cases return the version including country calling code. // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion return $this->format($number, PhoneNumberFormat::NATIONAL); } // Metadata cannot be null because we checked 'isValidRegionCode()' above. $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom); $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix(); // For regions that have multiple international prefixes, the international format of the // number is returned, unless there is a preferred international prefix. $internationalPrefixForFormatting = ''; $uniqueInternationalPrefixMatcher = new Matcher(static::SINGLE_INTERNATIONAL_PREFIX, $internationalPrefix); if ($uniqueInternationalPrefixMatcher->matches()) { $internationalPrefixForFormatting = $internationalPrefix; } elseif ($metadataForRegionCallingFrom->hasPreferredInternationalPrefix()) { $internationalPrefixForFormatting = $metadataForRegionCallingFrom->getPreferredInternationalPrefix(); } $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); // Metadata cannot be null because the country calling code is valid. $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode); $formattedNationalNumber = $this->formatNsn( $nationalSignificantNumber, $metadataForRegion, PhoneNumberFormat::INTERNATIONAL ); $formattedNumber = $formattedNationalNumber; $this->maybeAppendFormattedExtension( $number, $metadataForRegion, PhoneNumberFormat::INTERNATIONAL, $formattedNumber ); if (mb_strlen($internationalPrefixForFormatting) > 0) { $formattedNumber = $internationalPrefixForFormatting . ' ' . $countryCallingCode . ' ' . $formattedNumber; } else { $this->prefixNumberWithCountryCallingCode( $countryCallingCode, PhoneNumberFormat::INTERNATIONAL, $formattedNumber ); } return $formattedNumber; }
php
public function formatOutOfCountryCallingNumber(PhoneNumber $number, $regionCallingFrom) { if (!$this->isValidRegionCode($regionCallingFrom)) { return $this->format($number, PhoneNumberFormat::INTERNATIONAL); } $countryCallingCode = $number->getCountryCode(); $nationalSignificantNumber = $this->getNationalSignificantNumber($number); if (!$this->hasValidCountryCallingCode($countryCallingCode)) { return $nationalSignificantNumber; } if ($countryCallingCode == static::NANPA_COUNTRY_CODE) { if ($this->isNANPACountry($regionCallingFrom)) { // For NANPA regions, return the national format for these regions but prefix it with the // country calling code. return $countryCallingCode . ' ' . $this->format($number, PhoneNumberFormat::NATIONAL); } } elseif ($countryCallingCode == $this->getCountryCodeForValidRegion($regionCallingFrom)) { // If regions share a country calling code, the country calling code need not be dialled. // This also applies when dialling within a region, so this if clause covers both these cases. // Technically this is the case for dialling from La Reunion to other overseas departments of // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this // edge case for now and for those cases return the version including country calling code. // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion return $this->format($number, PhoneNumberFormat::NATIONAL); } // Metadata cannot be null because we checked 'isValidRegionCode()' above. $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom); $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix(); // For regions that have multiple international prefixes, the international format of the // number is returned, unless there is a preferred international prefix. $internationalPrefixForFormatting = ''; $uniqueInternationalPrefixMatcher = new Matcher(static::SINGLE_INTERNATIONAL_PREFIX, $internationalPrefix); if ($uniqueInternationalPrefixMatcher->matches()) { $internationalPrefixForFormatting = $internationalPrefix; } elseif ($metadataForRegionCallingFrom->hasPreferredInternationalPrefix()) { $internationalPrefixForFormatting = $metadataForRegionCallingFrom->getPreferredInternationalPrefix(); } $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); // Metadata cannot be null because the country calling code is valid. $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode); $formattedNationalNumber = $this->formatNsn( $nationalSignificantNumber, $metadataForRegion, PhoneNumberFormat::INTERNATIONAL ); $formattedNumber = $formattedNationalNumber; $this->maybeAppendFormattedExtension( $number, $metadataForRegion, PhoneNumberFormat::INTERNATIONAL, $formattedNumber ); if (mb_strlen($internationalPrefixForFormatting) > 0) { $formattedNumber = $internationalPrefixForFormatting . ' ' . $countryCallingCode . ' ' . $formattedNumber; } else { $this->prefixNumberWithCountryCallingCode( $countryCallingCode, PhoneNumberFormat::INTERNATIONAL, $formattedNumber ); } return $formattedNumber; }
[ "public", "function", "formatOutOfCountryCallingNumber", "(", "PhoneNumber", "$", "number", ",", "$", "regionCallingFrom", ")", "{", "if", "(", "!", "$", "this", "->", "isValidRegionCode", "(", "$", "regionCallingFrom", ")", ")", "{", "return", "$", "this", "->", "format", "(", "$", "number", ",", "PhoneNumberFormat", "::", "INTERNATIONAL", ")", ";", "}", "$", "countryCallingCode", "=", "$", "number", "->", "getCountryCode", "(", ")", ";", "$", "nationalSignificantNumber", "=", "$", "this", "->", "getNationalSignificantNumber", "(", "$", "number", ")", ";", "if", "(", "!", "$", "this", "->", "hasValidCountryCallingCode", "(", "$", "countryCallingCode", ")", ")", "{", "return", "$", "nationalSignificantNumber", ";", "}", "if", "(", "$", "countryCallingCode", "==", "static", "::", "NANPA_COUNTRY_CODE", ")", "{", "if", "(", "$", "this", "->", "isNANPACountry", "(", "$", "regionCallingFrom", ")", ")", "{", "// For NANPA regions, return the national format for these regions but prefix it with the", "// country calling code.", "return", "$", "countryCallingCode", ".", "' '", ".", "$", "this", "->", "format", "(", "$", "number", ",", "PhoneNumberFormat", "::", "NATIONAL", ")", ";", "}", "}", "elseif", "(", "$", "countryCallingCode", "==", "$", "this", "->", "getCountryCodeForValidRegion", "(", "$", "regionCallingFrom", ")", ")", "{", "// If regions share a country calling code, the country calling code need not be dialled.", "// This also applies when dialling within a region, so this if clause covers both these cases.", "// Technically this is the case for dialling from La Reunion to other overseas departments of", "// France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this", "// edge case for now and for those cases return the version including country calling code.", "// Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion", "return", "$", "this", "->", "format", "(", "$", "number", ",", "PhoneNumberFormat", "::", "NATIONAL", ")", ";", "}", "// Metadata cannot be null because we checked 'isValidRegionCode()' above.", "$", "metadataForRegionCallingFrom", "=", "$", "this", "->", "getMetadataForRegion", "(", "$", "regionCallingFrom", ")", ";", "$", "internationalPrefix", "=", "$", "metadataForRegionCallingFrom", "->", "getInternationalPrefix", "(", ")", ";", "// For regions that have multiple international prefixes, the international format of the", "// number is returned, unless there is a preferred international prefix.", "$", "internationalPrefixForFormatting", "=", "''", ";", "$", "uniqueInternationalPrefixMatcher", "=", "new", "Matcher", "(", "static", "::", "SINGLE_INTERNATIONAL_PREFIX", ",", "$", "internationalPrefix", ")", ";", "if", "(", "$", "uniqueInternationalPrefixMatcher", "->", "matches", "(", ")", ")", "{", "$", "internationalPrefixForFormatting", "=", "$", "internationalPrefix", ";", "}", "elseif", "(", "$", "metadataForRegionCallingFrom", "->", "hasPreferredInternationalPrefix", "(", ")", ")", "{", "$", "internationalPrefixForFormatting", "=", "$", "metadataForRegionCallingFrom", "->", "getPreferredInternationalPrefix", "(", ")", ";", "}", "$", "regionCode", "=", "$", "this", "->", "getRegionCodeForCountryCode", "(", "$", "countryCallingCode", ")", ";", "// Metadata cannot be null because the country calling code is valid.", "$", "metadataForRegion", "=", "$", "this", "->", "getMetadataForRegionOrCallingCode", "(", "$", "countryCallingCode", ",", "$", "regionCode", ")", ";", "$", "formattedNationalNumber", "=", "$", "this", "->", "formatNsn", "(", "$", "nationalSignificantNumber", ",", "$", "metadataForRegion", ",", "PhoneNumberFormat", "::", "INTERNATIONAL", ")", ";", "$", "formattedNumber", "=", "$", "formattedNationalNumber", ";", "$", "this", "->", "maybeAppendFormattedExtension", "(", "$", "number", ",", "$", "metadataForRegion", ",", "PhoneNumberFormat", "::", "INTERNATIONAL", ",", "$", "formattedNumber", ")", ";", "if", "(", "mb_strlen", "(", "$", "internationalPrefixForFormatting", ")", ">", "0", ")", "{", "$", "formattedNumber", "=", "$", "internationalPrefixForFormatting", ".", "' '", ".", "$", "countryCallingCode", ".", "' '", ".", "$", "formattedNumber", ";", "}", "else", "{", "$", "this", "->", "prefixNumberWithCountryCallingCode", "(", "$", "countryCallingCode", ",", "PhoneNumberFormat", "::", "INTERNATIONAL", ",", "$", "formattedNumber", ")", ";", "}", "return", "$", "formattedNumber", ";", "}" ]
Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is supplied, we format the number in its INTERNATIONAL format. If the country calling code is the same as that of the region where the number is from, then NATIONAL formatting will be applied. <p>If the number itself has a country calling code of zero or an otherwise invalid country calling code, then we return the number with no formatting applied. <p>Note this function takes care of the case for calling inside of NANPA and between Russia and Kazakhstan (who share the same country calling code). In those cases, no international prefix is used. For regions which have multiple international prefixes, the number in its INTERNATIONAL format will be returned instead. @param PhoneNumber $number the phone number to be formatted @param string $regionCallingFrom the region where the call is being placed @return string the formatted phone number
[ "Formats", "a", "phone", "number", "for", "out", "-", "of", "-", "country", "dialing", "purposes", ".", "If", "no", "regionCallingFrom", "is", "supplied", "we", "format", "the", "number", "in", "its", "INTERNATIONAL", "format", ".", "If", "the", "country", "calling", "code", "is", "the", "same", "as", "that", "of", "the", "region", "where", "the", "number", "is", "from", "then", "NATIONAL", "formatting", "will", "be", "applied", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L2670-L2736
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.rawInputContainsNationalPrefix
protected function rawInputContainsNationalPrefix($rawInput, $nationalPrefix, $regionCode) { $normalizedNationalNumber = static::normalizeDigitsOnly($rawInput); if (strpos($normalizedNationalNumber, $nationalPrefix) === 0) { try { // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we // check the validity of the number if the assumed national prefix is removed (777123 won't // be valid in Japan). return $this->isValidNumber( $this->parse(substr($normalizedNationalNumber, mb_strlen($nationalPrefix)), $regionCode) ); } catch (NumberParseException $e) { return false; } } return false; }
php
protected function rawInputContainsNationalPrefix($rawInput, $nationalPrefix, $regionCode) { $normalizedNationalNumber = static::normalizeDigitsOnly($rawInput); if (strpos($normalizedNationalNumber, $nationalPrefix) === 0) { try { // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we // check the validity of the number if the assumed national prefix is removed (777123 won't // be valid in Japan). return $this->isValidNumber( $this->parse(substr($normalizedNationalNumber, mb_strlen($nationalPrefix)), $regionCode) ); } catch (NumberParseException $e) { return false; } } return false; }
[ "protected", "function", "rawInputContainsNationalPrefix", "(", "$", "rawInput", ",", "$", "nationalPrefix", ",", "$", "regionCode", ")", "{", "$", "normalizedNationalNumber", "=", "static", "::", "normalizeDigitsOnly", "(", "$", "rawInput", ")", ";", "if", "(", "strpos", "(", "$", "normalizedNationalNumber", ",", "$", "nationalPrefix", ")", "===", "0", ")", "{", "try", "{", "// Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix", "// when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we", "// check the validity of the number if the assumed national prefix is removed (777123 won't", "// be valid in Japan).", "return", "$", "this", "->", "isValidNumber", "(", "$", "this", "->", "parse", "(", "substr", "(", "$", "normalizedNationalNumber", ",", "mb_strlen", "(", "$", "nationalPrefix", ")", ")", ",", "$", "regionCode", ")", ")", ";", "}", "catch", "(", "NumberParseException", "$", "e", ")", "{", "return", "false", ";", "}", "}", "return", "false", ";", "}" ]
Check if rawInput, which is assumed to be in the national format, has a national prefix. The national prefix is assumed to be in digits-only form. @param string $rawInput @param string $nationalPrefix @param string $regionCode @return bool
[ "Check", "if", "rawInput", "which", "is", "assumed", "to", "be", "in", "the", "national", "format", "has", "a", "national", "prefix", ".", "The", "national", "prefix", "is", "assumed", "to", "be", "in", "digits", "-", "only", "form", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L2918-L2935
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.formatByPattern
public function formatByPattern(PhoneNumber $number, $numberFormat, array $userDefinedFormats) { $countryCallingCode = $number->getCountryCode(); $nationalSignificantNumber = $this->getNationalSignificantNumber($number); if (!$this->hasValidCountryCallingCode($countryCallingCode)) { return $nationalSignificantNumber; } // Note getRegionCodeForCountryCode() is used because formatting information for regions which // share a country calling code is contained by only one region for performance reasons. For // example, for NANPA regions it will be contained in the metadata for US. $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); // Metadata cannot be null because the country calling code is valid $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode); $formattedNumber = ''; $formattingPattern = $this->chooseFormattingPatternForNumber($userDefinedFormats, $nationalSignificantNumber); if ($formattingPattern === null) { // If no pattern above is matched, we format the number as a whole. $formattedNumber .= $nationalSignificantNumber; } else { $numFormatCopy = new NumberFormat(); // Before we do a replacement of the national prefix pattern $NP with the national prefix, we // need to copy the rule so that subsequent replacements for different numbers have the // appropriate national prefix. $numFormatCopy->mergeFrom($formattingPattern); $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule(); if (mb_strlen($nationalPrefixFormattingRule) > 0) { $nationalPrefix = $metadata->getNationalPrefix(); if (mb_strlen($nationalPrefix) > 0) { // Replace $NP with national prefix and $FG with the first group ($1). $nationalPrefixFormattingRule = str_replace(array(static::NP_STRING, static::FG_STRING), array($nationalPrefix, '$1'), $nationalPrefixFormattingRule); $numFormatCopy->setNationalPrefixFormattingRule($nationalPrefixFormattingRule); } else { // We don't want to have a rule for how to format the national prefix if there isn't one. $numFormatCopy->clearNationalPrefixFormattingRule(); } } $formattedNumber .= $this->formatNsnUsingPattern($nationalSignificantNumber, $numFormatCopy, $numberFormat); } $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber); $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber); return $formattedNumber; }
php
public function formatByPattern(PhoneNumber $number, $numberFormat, array $userDefinedFormats) { $countryCallingCode = $number->getCountryCode(); $nationalSignificantNumber = $this->getNationalSignificantNumber($number); if (!$this->hasValidCountryCallingCode($countryCallingCode)) { return $nationalSignificantNumber; } // Note getRegionCodeForCountryCode() is used because formatting information for regions which // share a country calling code is contained by only one region for performance reasons. For // example, for NANPA regions it will be contained in the metadata for US. $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); // Metadata cannot be null because the country calling code is valid $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode); $formattedNumber = ''; $formattingPattern = $this->chooseFormattingPatternForNumber($userDefinedFormats, $nationalSignificantNumber); if ($formattingPattern === null) { // If no pattern above is matched, we format the number as a whole. $formattedNumber .= $nationalSignificantNumber; } else { $numFormatCopy = new NumberFormat(); // Before we do a replacement of the national prefix pattern $NP with the national prefix, we // need to copy the rule so that subsequent replacements for different numbers have the // appropriate national prefix. $numFormatCopy->mergeFrom($formattingPattern); $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule(); if (mb_strlen($nationalPrefixFormattingRule) > 0) { $nationalPrefix = $metadata->getNationalPrefix(); if (mb_strlen($nationalPrefix) > 0) { // Replace $NP with national prefix and $FG with the first group ($1). $nationalPrefixFormattingRule = str_replace(array(static::NP_STRING, static::FG_STRING), array($nationalPrefix, '$1'), $nationalPrefixFormattingRule); $numFormatCopy->setNationalPrefixFormattingRule($nationalPrefixFormattingRule); } else { // We don't want to have a rule for how to format the national prefix if there isn't one. $numFormatCopy->clearNationalPrefixFormattingRule(); } } $formattedNumber .= $this->formatNsnUsingPattern($nationalSignificantNumber, $numFormatCopy, $numberFormat); } $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber); $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber); return $formattedNumber; }
[ "public", "function", "formatByPattern", "(", "PhoneNumber", "$", "number", ",", "$", "numberFormat", ",", "array", "$", "userDefinedFormats", ")", "{", "$", "countryCallingCode", "=", "$", "number", "->", "getCountryCode", "(", ")", ";", "$", "nationalSignificantNumber", "=", "$", "this", "->", "getNationalSignificantNumber", "(", "$", "number", ")", ";", "if", "(", "!", "$", "this", "->", "hasValidCountryCallingCode", "(", "$", "countryCallingCode", ")", ")", "{", "return", "$", "nationalSignificantNumber", ";", "}", "// Note getRegionCodeForCountryCode() is used because formatting information for regions which", "// share a country calling code is contained by only one region for performance reasons. For", "// example, for NANPA regions it will be contained in the metadata for US.", "$", "regionCode", "=", "$", "this", "->", "getRegionCodeForCountryCode", "(", "$", "countryCallingCode", ")", ";", "// Metadata cannot be null because the country calling code is valid", "$", "metadata", "=", "$", "this", "->", "getMetadataForRegionOrCallingCode", "(", "$", "countryCallingCode", ",", "$", "regionCode", ")", ";", "$", "formattedNumber", "=", "''", ";", "$", "formattingPattern", "=", "$", "this", "->", "chooseFormattingPatternForNumber", "(", "$", "userDefinedFormats", ",", "$", "nationalSignificantNumber", ")", ";", "if", "(", "$", "formattingPattern", "===", "null", ")", "{", "// If no pattern above is matched, we format the number as a whole.", "$", "formattedNumber", ".=", "$", "nationalSignificantNumber", ";", "}", "else", "{", "$", "numFormatCopy", "=", "new", "NumberFormat", "(", ")", ";", "// Before we do a replacement of the national prefix pattern $NP with the national prefix, we", "// need to copy the rule so that subsequent replacements for different numbers have the", "// appropriate national prefix.", "$", "numFormatCopy", "->", "mergeFrom", "(", "$", "formattingPattern", ")", ";", "$", "nationalPrefixFormattingRule", "=", "$", "formattingPattern", "->", "getNationalPrefixFormattingRule", "(", ")", ";", "if", "(", "mb_strlen", "(", "$", "nationalPrefixFormattingRule", ")", ">", "0", ")", "{", "$", "nationalPrefix", "=", "$", "metadata", "->", "getNationalPrefix", "(", ")", ";", "if", "(", "mb_strlen", "(", "$", "nationalPrefix", ")", ">", "0", ")", "{", "// Replace $NP with national prefix and $FG with the first group ($1).", "$", "nationalPrefixFormattingRule", "=", "str_replace", "(", "array", "(", "static", "::", "NP_STRING", ",", "static", "::", "FG_STRING", ")", ",", "array", "(", "$", "nationalPrefix", ",", "'$1'", ")", ",", "$", "nationalPrefixFormattingRule", ")", ";", "$", "numFormatCopy", "->", "setNationalPrefixFormattingRule", "(", "$", "nationalPrefixFormattingRule", ")", ";", "}", "else", "{", "// We don't want to have a rule for how to format the national prefix if there isn't one.", "$", "numFormatCopy", "->", "clearNationalPrefixFormattingRule", "(", ")", ";", "}", "}", "$", "formattedNumber", ".=", "$", "this", "->", "formatNsnUsingPattern", "(", "$", "nationalSignificantNumber", ",", "$", "numFormatCopy", ",", "$", "numberFormat", ")", ";", "}", "$", "this", "->", "maybeAppendFormattedExtension", "(", "$", "number", ",", "$", "metadata", ",", "$", "numberFormat", ",", "$", "formattedNumber", ")", ";", "$", "this", "->", "prefixNumberWithCountryCallingCode", "(", "$", "countryCallingCode", ",", "$", "numberFormat", ",", "$", "formattedNumber", ")", ";", "return", "$", "formattedNumber", ";", "}" ]
Formats a phone number in the specified format using client-defined formatting rules. Note that if the phone number has a country calling code of zero or an otherwise invalid country calling code, we cannot work out things like whether there should be a national prefix applied, or how to format extensions, so we return the national significant number with no formatting applied. @param PhoneNumber $number the phone number to be formatted @param int $numberFormat the format the phone number should be formatted into @param array $userDefinedFormats formatting rules specified by clients @return String the formatted phone number
[ "Formats", "a", "phone", "number", "in", "the", "specified", "format", "using", "client", "-", "defined", "formatting", "rules", ".", "Note", "that", "if", "the", "phone", "number", "has", "a", "country", "calling", "code", "of", "zero", "or", "an", "otherwise", "invalid", "country", "calling", "code", "we", "cannot", "work", "out", "things", "like", "whether", "there", "should", "be", "a", "national", "prefix", "applied", "or", "how", "to", "format", "extensions", "so", "we", "return", "the", "national", "significant", "number", "with", "no", "formatting", "applied", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L3042-L3086
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.getExampleNumberForType
public function getExampleNumberForType($regionCodeOrType, $type = null) { if ($regionCodeOrType !== null && $type === null) { /* * Gets a valid number for the specified number type (it may belong to any country). */ foreach ($this->getSupportedRegions() as $regionCode) { $exampleNumber = $this->getExampleNumberForType($regionCode, $regionCodeOrType); if ($exampleNumber !== null) { return $exampleNumber; } } // If there wasn't an example number for a region, try the non-geographical entities foreach ($this->getSupportedGlobalNetworkCallingCodes() as $countryCallingCode) { $desc = $this->getNumberDescByType($this->getMetadataForNonGeographicalRegion($countryCallingCode), $regionCodeOrType); try { if ($desc->getExampleNumber() != '') { return $this->parse('+' . $countryCallingCode . $desc->getExampleNumber(), static::UNKNOWN_REGION); } } catch (NumberParseException $e) { // noop } } // There are no example numbers of this type for any country in the library. return null; } // Check the region code is valid. if (!$this->isValidRegionCode($regionCodeOrType)) { return null; } $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCodeOrType), $type); try { if ($desc->hasExampleNumber()) { return $this->parse($desc->getExampleNumber(), $regionCodeOrType); } } catch (NumberParseException $e) { // noop } return null; }
php
public function getExampleNumberForType($regionCodeOrType, $type = null) { if ($regionCodeOrType !== null && $type === null) { /* * Gets a valid number for the specified number type (it may belong to any country). */ foreach ($this->getSupportedRegions() as $regionCode) { $exampleNumber = $this->getExampleNumberForType($regionCode, $regionCodeOrType); if ($exampleNumber !== null) { return $exampleNumber; } } // If there wasn't an example number for a region, try the non-geographical entities foreach ($this->getSupportedGlobalNetworkCallingCodes() as $countryCallingCode) { $desc = $this->getNumberDescByType($this->getMetadataForNonGeographicalRegion($countryCallingCode), $regionCodeOrType); try { if ($desc->getExampleNumber() != '') { return $this->parse('+' . $countryCallingCode . $desc->getExampleNumber(), static::UNKNOWN_REGION); } } catch (NumberParseException $e) { // noop } } // There are no example numbers of this type for any country in the library. return null; } // Check the region code is valid. if (!$this->isValidRegionCode($regionCodeOrType)) { return null; } $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCodeOrType), $type); try { if ($desc->hasExampleNumber()) { return $this->parse($desc->getExampleNumber(), $regionCodeOrType); } } catch (NumberParseException $e) { // noop } return null; }
[ "public", "function", "getExampleNumberForType", "(", "$", "regionCodeOrType", ",", "$", "type", "=", "null", ")", "{", "if", "(", "$", "regionCodeOrType", "!==", "null", "&&", "$", "type", "===", "null", ")", "{", "/*\n * Gets a valid number for the specified number type (it may belong to any country).\n */", "foreach", "(", "$", "this", "->", "getSupportedRegions", "(", ")", "as", "$", "regionCode", ")", "{", "$", "exampleNumber", "=", "$", "this", "->", "getExampleNumberForType", "(", "$", "regionCode", ",", "$", "regionCodeOrType", ")", ";", "if", "(", "$", "exampleNumber", "!==", "null", ")", "{", "return", "$", "exampleNumber", ";", "}", "}", "// If there wasn't an example number for a region, try the non-geographical entities", "foreach", "(", "$", "this", "->", "getSupportedGlobalNetworkCallingCodes", "(", ")", "as", "$", "countryCallingCode", ")", "{", "$", "desc", "=", "$", "this", "->", "getNumberDescByType", "(", "$", "this", "->", "getMetadataForNonGeographicalRegion", "(", "$", "countryCallingCode", ")", ",", "$", "regionCodeOrType", ")", ";", "try", "{", "if", "(", "$", "desc", "->", "getExampleNumber", "(", ")", "!=", "''", ")", "{", "return", "$", "this", "->", "parse", "(", "'+'", ".", "$", "countryCallingCode", ".", "$", "desc", "->", "getExampleNumber", "(", ")", ",", "static", "::", "UNKNOWN_REGION", ")", ";", "}", "}", "catch", "(", "NumberParseException", "$", "e", ")", "{", "// noop", "}", "}", "// There are no example numbers of this type for any country in the library.", "return", "null", ";", "}", "// Check the region code is valid.", "if", "(", "!", "$", "this", "->", "isValidRegionCode", "(", "$", "regionCodeOrType", ")", ")", "{", "return", "null", ";", "}", "$", "desc", "=", "$", "this", "->", "getNumberDescByType", "(", "$", "this", "->", "getMetadataForRegion", "(", "$", "regionCodeOrType", ")", ",", "$", "type", ")", ";", "try", "{", "if", "(", "$", "desc", "->", "hasExampleNumber", "(", ")", ")", "{", "return", "$", "this", "->", "parse", "(", "$", "desc", "->", "getExampleNumber", "(", ")", ",", "$", "regionCodeOrType", ")", ";", "}", "}", "catch", "(", "NumberParseException", "$", "e", ")", "{", "// noop", "}", "return", "null", ";", "}" ]
Gets a valid number for the specified region and number type. @param string|int $regionCodeOrType the region for which an example number is needed @param int $type the PhoneNumberType of number that is needed @return PhoneNumber a valid number for the specified region and type. Returns null when the metadata does not contain such information or if an invalid region or region 001 was entered. For 001 (representing non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead. If $regionCodeOrType is the only parameter supplied, then a valid number for the specified number type will be returned that may belong to any country.
[ "Gets", "a", "valid", "number", "for", "the", "specified", "region", "and", "number", "type", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L3172-L3213
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.getExampleNumberForNonGeoEntity
public function getExampleNumberForNonGeoEntity($countryCallingCode) { $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode); if ($metadata !== null) { // For geographical entities, fixed-line data is always present. However, for non-geographical // entities, this is not the case, so we have to go through different types to find the // example number. We don't check fixed-line or personal number since they aren't used by // non-geographical entities (if this changes, a unit-test will catch this.) /** @var PhoneNumberDesc[] $list */ $list = array( $metadata->getMobile(), $metadata->getTollFree(), $metadata->getSharedCost(), $metadata->getVoip(), $metadata->getVoicemail(), $metadata->getUan(), $metadata->getPremiumRate(), ); foreach ($list as $desc) { try { if ($desc !== null && $desc->hasExampleNumber()) { return $this->parse('+' . $countryCallingCode . $desc->getExampleNumber(), self::UNKNOWN_REGION); } } catch (NumberParseException $e) { // noop } } } return null; }
php
public function getExampleNumberForNonGeoEntity($countryCallingCode) { $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode); if ($metadata !== null) { // For geographical entities, fixed-line data is always present. However, for non-geographical // entities, this is not the case, so we have to go through different types to find the // example number. We don't check fixed-line or personal number since they aren't used by // non-geographical entities (if this changes, a unit-test will catch this.) /** @var PhoneNumberDesc[] $list */ $list = array( $metadata->getMobile(), $metadata->getTollFree(), $metadata->getSharedCost(), $metadata->getVoip(), $metadata->getVoicemail(), $metadata->getUan(), $metadata->getPremiumRate(), ); foreach ($list as $desc) { try { if ($desc !== null && $desc->hasExampleNumber()) { return $this->parse('+' . $countryCallingCode . $desc->getExampleNumber(), self::UNKNOWN_REGION); } } catch (NumberParseException $e) { // noop } } } return null; }
[ "public", "function", "getExampleNumberForNonGeoEntity", "(", "$", "countryCallingCode", ")", "{", "$", "metadata", "=", "$", "this", "->", "getMetadataForNonGeographicalRegion", "(", "$", "countryCallingCode", ")", ";", "if", "(", "$", "metadata", "!==", "null", ")", "{", "// For geographical entities, fixed-line data is always present. However, for non-geographical", "// entities, this is not the case, so we have to go through different types to find the", "// example number. We don't check fixed-line or personal number since they aren't used by", "// non-geographical entities (if this changes, a unit-test will catch this.)", "/** @var PhoneNumberDesc[] $list */", "$", "list", "=", "array", "(", "$", "metadata", "->", "getMobile", "(", ")", ",", "$", "metadata", "->", "getTollFree", "(", ")", ",", "$", "metadata", "->", "getSharedCost", "(", ")", ",", "$", "metadata", "->", "getVoip", "(", ")", ",", "$", "metadata", "->", "getVoicemail", "(", ")", ",", "$", "metadata", "->", "getUan", "(", ")", ",", "$", "metadata", "->", "getPremiumRate", "(", ")", ",", ")", ";", "foreach", "(", "$", "list", "as", "$", "desc", ")", "{", "try", "{", "if", "(", "$", "desc", "!==", "null", "&&", "$", "desc", "->", "hasExampleNumber", "(", ")", ")", "{", "return", "$", "this", "->", "parse", "(", "'+'", ".", "$", "countryCallingCode", ".", "$", "desc", "->", "getExampleNumber", "(", ")", ",", "self", "::", "UNKNOWN_REGION", ")", ";", "}", "}", "catch", "(", "NumberParseException", "$", "e", ")", "{", "// noop", "}", "}", "}", "return", "null", ";", "}" ]
Gets a valid number for the specified country calling code for a non-geographical entity. @param int $countryCallingCode the country calling code for a non-geographical entity @return PhoneNumber a valid number for the non-geographical entity. Returns null when the metadata does not contain such information, or the country calling code passed in does not belong to a non-geographical entity.
[ "Gets", "a", "valid", "number", "for", "the", "specified", "country", "calling", "code", "for", "a", "non", "-", "geographical", "entity", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L3257-L3286
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.isNationalNumberSuffixOfTheOther
protected function isNationalNumberSuffixOfTheOther(PhoneNumber $firstNumber, PhoneNumber $secondNumber) { $firstNumberNationalNumber = trim((string)$firstNumber->getNationalNumber()); $secondNumberNationalNumber = trim((string)$secondNumber->getNationalNumber()); return $this->stringEndsWithString($firstNumberNationalNumber, $secondNumberNationalNumber) || $this->stringEndsWithString($secondNumberNationalNumber, $firstNumberNationalNumber); }
php
protected function isNationalNumberSuffixOfTheOther(PhoneNumber $firstNumber, PhoneNumber $secondNumber) { $firstNumberNationalNumber = trim((string)$firstNumber->getNationalNumber()); $secondNumberNationalNumber = trim((string)$secondNumber->getNationalNumber()); return $this->stringEndsWithString($firstNumberNationalNumber, $secondNumberNationalNumber) || $this->stringEndsWithString($secondNumberNationalNumber, $firstNumberNationalNumber); }
[ "protected", "function", "isNationalNumberSuffixOfTheOther", "(", "PhoneNumber", "$", "firstNumber", ",", "PhoneNumber", "$", "secondNumber", ")", "{", "$", "firstNumberNationalNumber", "=", "trim", "(", "(", "string", ")", "$", "firstNumber", "->", "getNationalNumber", "(", ")", ")", ";", "$", "secondNumberNationalNumber", "=", "trim", "(", "(", "string", ")", "$", "secondNumber", "->", "getNationalNumber", "(", ")", ")", ";", "return", "$", "this", "->", "stringEndsWithString", "(", "$", "firstNumberNationalNumber", ",", "$", "secondNumberNationalNumber", ")", "||", "$", "this", "->", "stringEndsWithString", "(", "$", "secondNumberNationalNumber", ",", "$", "firstNumberNationalNumber", ")", ";", "}" ]
Returns true when one national number is the suffix of the other or both are the same. @param PhoneNumber $firstNumber @param PhoneNumber $secondNumber @return bool
[ "Returns", "true", "when", "one", "national", "number", "is", "the", "suffix", "of", "the", "other", "or", "both", "are", "the", "same", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L3424-L3430
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.isMobileNumberPortableRegion
public function isMobileNumberPortableRegion($regionCode) { $metadata = $this->getMetadataForRegion($regionCode); if ($metadata === null) { return false; } return $metadata->isMobileNumberPortableRegion(); }
php
public function isMobileNumberPortableRegion($regionCode) { $metadata = $this->getMetadataForRegion($regionCode); if ($metadata === null) { return false; } return $metadata->isMobileNumberPortableRegion(); }
[ "public", "function", "isMobileNumberPortableRegion", "(", "$", "regionCode", ")", "{", "$", "metadata", "=", "$", "this", "->", "getMetadataForRegion", "(", "$", "regionCode", ")", ";", "if", "(", "$", "metadata", "===", "null", ")", "{", "return", "false", ";", "}", "return", "$", "metadata", "->", "isMobileNumberPortableRegion", "(", ")", ";", "}" ]
Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability. @param string $regionCode the region for which we want to know whether it supports mobile number portability or not. @return bool
[ "Returns", "true", "if", "the", "supplied", "region", "supports", "mobile", "number", "portability", ".", "Returns", "false", "for", "invalid", "unknown", "or", "regions", "that", "don", "t", "support", "mobile", "number", "portability", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L3447-L3455
train
giggsey/libphonenumber-for-php
src/PhoneNumberUtil.php
PhoneNumberUtil.truncateTooLongNumber
public function truncateTooLongNumber(PhoneNumber $number) { if ($this->isValidNumber($number)) { return true; } $numberCopy = new PhoneNumber(); $numberCopy->mergeFrom($number); $nationalNumber = $number->getNationalNumber(); do { $nationalNumber = floor($nationalNumber / 10); $numberCopy->setNationalNumber($nationalNumber); if ($this->isPossibleNumberWithReason($numberCopy) == ValidationResult::TOO_SHORT || $nationalNumber == 0) { return false; } } while (!$this->isValidNumber($numberCopy)); $number->setNationalNumber($nationalNumber); return true; }
php
public function truncateTooLongNumber(PhoneNumber $number) { if ($this->isValidNumber($number)) { return true; } $numberCopy = new PhoneNumber(); $numberCopy->mergeFrom($number); $nationalNumber = $number->getNationalNumber(); do { $nationalNumber = floor($nationalNumber / 10); $numberCopy->setNationalNumber($nationalNumber); if ($this->isPossibleNumberWithReason($numberCopy) == ValidationResult::TOO_SHORT || $nationalNumber == 0) { return false; } } while (!$this->isValidNumber($numberCopy)); $number->setNationalNumber($nationalNumber); return true; }
[ "public", "function", "truncateTooLongNumber", "(", "PhoneNumber", "$", "number", ")", "{", "if", "(", "$", "this", "->", "isValidNumber", "(", "$", "number", ")", ")", "{", "return", "true", ";", "}", "$", "numberCopy", "=", "new", "PhoneNumber", "(", ")", ";", "$", "numberCopy", "->", "mergeFrom", "(", "$", "number", ")", ";", "$", "nationalNumber", "=", "$", "number", "->", "getNationalNumber", "(", ")", ";", "do", "{", "$", "nationalNumber", "=", "floor", "(", "$", "nationalNumber", "/", "10", ")", ";", "$", "numberCopy", "->", "setNationalNumber", "(", "$", "nationalNumber", ")", ";", "if", "(", "$", "this", "->", "isPossibleNumberWithReason", "(", "$", "numberCopy", ")", "==", "ValidationResult", "::", "TOO_SHORT", "||", "$", "nationalNumber", "==", "0", ")", "{", "return", "false", ";", "}", "}", "while", "(", "!", "$", "this", "->", "isValidNumber", "(", "$", "numberCopy", ")", ")", ";", "$", "number", "->", "setNationalNumber", "(", "$", "nationalNumber", ")", ";", "return", "true", ";", "}" ]
Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version. If no valid number could be extracted, the PhoneNumber object passed in will not be modified. @param PhoneNumber $number a PhoneNumber object which contains a number that is too long to be valid. @return boolean true if a valid phone number can be successfully extracted.
[ "Attempts", "to", "extract", "a", "valid", "number", "from", "a", "phone", "number", "that", "is", "too", "long", "to", "be", "valid", "and", "resets", "the", "PhoneNumber", "object", "passed", "in", "to", "that", "valid", "version", ".", "If", "no", "valid", "number", "could", "be", "extracted", "the", "PhoneNumber", "object", "passed", "in", "will", "not", "be", "modified", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberUtil.php#L3582-L3599
train
giggsey/libphonenumber-for-php
src/PhoneNumberToTimeZonesMapper.php
PhoneNumberToTimeZonesMapper.getTimeZonesForGeocodableNumber
protected function getTimeZonesForGeocodableNumber(PhoneNumber $number) { $timezones = $this->prefixTimeZonesMap->lookupTimeZonesForNumber($number); return (count($timezones) == 0) ? $this->unknownTimeZoneList : $timezones; }
php
protected function getTimeZonesForGeocodableNumber(PhoneNumber $number) { $timezones = $this->prefixTimeZonesMap->lookupTimeZonesForNumber($number); return (count($timezones) == 0) ? $this->unknownTimeZoneList : $timezones; }
[ "protected", "function", "getTimeZonesForGeocodableNumber", "(", "PhoneNumber", "$", "number", ")", "{", "$", "timezones", "=", "$", "this", "->", "prefixTimeZonesMap", "->", "lookupTimeZonesForNumber", "(", "$", "number", ")", ";", "return", "(", "count", "(", "$", "timezones", ")", "==", "0", ")", "?", "$", "this", "->", "unknownTimeZoneList", ":", "$", "timezones", ";", "}" ]
Returns a list of time zones to which a geocodable phone number belongs. @param PhoneNumber $number The phone number for which we want to get the time zones to which it belongs @return array the list of correspondiing time zones or a single element list with the default unknown timezone if no other time zone was found or if the number was invalid
[ "Returns", "a", "list", "of", "time", "zones", "to", "which", "a", "geocodable", "phone", "number", "belongs", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberToTimeZonesMapper.php#L138-L142
train
giggsey/libphonenumber-for-php
src/prefixmapper/PrefixFileReader.php
PrefixFileReader.getDescriptionForNumber
public function getDescriptionForNumber(PhoneNumber $number, $language, $script, $region) { $phonePrefix = $number->getCountryCode() . PhoneNumberUtil::getInstance()->getNationalSignificantNumber($number); $phonePrefixDescriptions = $this->getPhonePrefixDescriptions($phonePrefix, $language, $script, $region); $description = ($phonePrefixDescriptions !== null) ? $phonePrefixDescriptions->lookup($number) : null; // When a location is not available in the requested language, fall back to English. if (($description === null || strlen($description) === 0) && $this->mayFallBackToEnglish($language)) { $defaultMap = $this->getPhonePrefixDescriptions($phonePrefix, 'en', '', ''); if ($defaultMap === null) { return ''; } $description = $defaultMap->lookup($number); } return ($description !== null) ? $description : ''; }
php
public function getDescriptionForNumber(PhoneNumber $number, $language, $script, $region) { $phonePrefix = $number->getCountryCode() . PhoneNumberUtil::getInstance()->getNationalSignificantNumber($number); $phonePrefixDescriptions = $this->getPhonePrefixDescriptions($phonePrefix, $language, $script, $region); $description = ($phonePrefixDescriptions !== null) ? $phonePrefixDescriptions->lookup($number) : null; // When a location is not available in the requested language, fall back to English. if (($description === null || strlen($description) === 0) && $this->mayFallBackToEnglish($language)) { $defaultMap = $this->getPhonePrefixDescriptions($phonePrefix, 'en', '', ''); if ($defaultMap === null) { return ''; } $description = $defaultMap->lookup($number); } return ($description !== null) ? $description : ''; }
[ "public", "function", "getDescriptionForNumber", "(", "PhoneNumber", "$", "number", ",", "$", "language", ",", "$", "script", ",", "$", "region", ")", "{", "$", "phonePrefix", "=", "$", "number", "->", "getCountryCode", "(", ")", ".", "PhoneNumberUtil", "::", "getInstance", "(", ")", "->", "getNationalSignificantNumber", "(", "$", "number", ")", ";", "$", "phonePrefixDescriptions", "=", "$", "this", "->", "getPhonePrefixDescriptions", "(", "$", "phonePrefix", ",", "$", "language", ",", "$", "script", ",", "$", "region", ")", ";", "$", "description", "=", "(", "$", "phonePrefixDescriptions", "!==", "null", ")", "?", "$", "phonePrefixDescriptions", "->", "lookup", "(", "$", "number", ")", ":", "null", ";", "// When a location is not available in the requested language, fall back to English.", "if", "(", "(", "$", "description", "===", "null", "||", "strlen", "(", "$", "description", ")", "===", "0", ")", "&&", "$", "this", "->", "mayFallBackToEnglish", "(", "$", "language", ")", ")", "{", "$", "defaultMap", "=", "$", "this", "->", "getPhonePrefixDescriptions", "(", "$", "phonePrefix", ",", "'en'", ",", "''", ",", "''", ")", ";", "if", "(", "$", "defaultMap", "===", "null", ")", "{", "return", "''", ";", "}", "$", "description", "=", "$", "defaultMap", "->", "lookup", "(", "$", "number", ")", ";", "}", "return", "(", "$", "description", "!==", "null", ")", "?", "$", "description", ":", "''", ";", "}" ]
Returns a text description in the given language for the given phone number. @param PhoneNumber $number the phone number for which we want to get a text description @param string $language two or three-letter lowercase ISO language as defined by ISO 639 @param string $script four-letter titlecase (the first letter is uppercase and the rest of the letters are lowercase) ISO script code as defined in ISO 15924 @param string $region two-letter uppercase ISO country code as defined by ISO 3166-1 @return string a text description for the given language code for the given phone number, or empty string if the number passed in is invalid or could belong to multiple countries
[ "Returns", "a", "text", "description", "in", "the", "given", "language", "for", "the", "given", "phone", "number", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/prefixmapper/PrefixFileReader.php#L102-L119
train
giggsey/libphonenumber-for-php
build/BuildMetadataFromXml.php
BuildMetadataFromXml.getMetadataFilter
public static function getMetadataFilter($liteBuild, $specialBuild) { if ($specialBuild) { if ($liteBuild) { throw new \RuntimeException('liteBuild and specialBuild may not both be set'); } return MetadataFilter::forSpecialBuild(); } if ($liteBuild) { return MetadataFilter::forLiteBuild(); } return MetadataFilter::emptyFilter(); }
php
public static function getMetadataFilter($liteBuild, $specialBuild) { if ($specialBuild) { if ($liteBuild) { throw new \RuntimeException('liteBuild and specialBuild may not both be set'); } return MetadataFilter::forSpecialBuild(); } if ($liteBuild) { return MetadataFilter::forLiteBuild(); } return MetadataFilter::emptyFilter(); }
[ "public", "static", "function", "getMetadataFilter", "(", "$", "liteBuild", ",", "$", "specialBuild", ")", "{", "if", "(", "$", "specialBuild", ")", "{", "if", "(", "$", "liteBuild", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'liteBuild and specialBuild may not both be set'", ")", ";", "}", "return", "MetadataFilter", "::", "forSpecialBuild", "(", ")", ";", "}", "if", "(", "$", "liteBuild", ")", "{", "return", "MetadataFilter", "::", "forLiteBuild", "(", ")", ";", "}", "return", "MetadataFilter", "::", "emptyFilter", "(", ")", ";", "}" ]
Processes the custom build flags and gets a MetadataFilter which may be used to filter PhoneMetadata objects. Incompatible flag combinations throw RuntimeException. @param bool $liteBuild @param bool $specialBuild @return MetadataFilter
[ "Processes", "the", "custom", "build", "flags", "and", "gets", "a", "MetadataFilter", "which", "may", "be", "used", "to", "filter", "PhoneMetadata", "objects", ".", "Incompatible", "flag", "combinations", "throw", "RuntimeException", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/BuildMetadataFromXml.php#L156-L169
train
giggsey/libphonenumber-for-php
build/BuildMetadataFromXml.php
BuildMetadataFromXml.getNationalPrefix
public static function getNationalPrefix(\DOMElement $element) { return $element->hasAttribute(self::NATIONAL_PREFIX) ? $element->getAttribute(self::NATIONAL_PREFIX) : ''; }
php
public static function getNationalPrefix(\DOMElement $element) { return $element->hasAttribute(self::NATIONAL_PREFIX) ? $element->getAttribute(self::NATIONAL_PREFIX) : ''; }
[ "public", "static", "function", "getNationalPrefix", "(", "\\", "DOMElement", "$", "element", ")", "{", "return", "$", "element", "->", "hasAttribute", "(", "self", "::", "NATIONAL_PREFIX", ")", "?", "$", "element", "->", "getAttribute", "(", "self", "::", "NATIONAL_PREFIX", ")", ":", "''", ";", "}" ]
Returns the national prefix of the provided country element. @internal @param \DOMElement $element @return string
[ "Returns", "the", "national", "prefix", "of", "the", "provided", "country", "element", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/BuildMetadataFromXml.php#L177-L180
train
giggsey/libphonenumber-for-php
build/BuildMetadataFromXml.php
BuildMetadataFromXml.loadNationalFormat
public static function loadNationalFormat( PhoneMetadata $metadata, \DOMElement $numberFormatElement, NumberFormat $format ) { self::setLeadingDigitsPatterns($numberFormatElement, $format); $format->setPattern(self::validateRE($numberFormatElement->getAttribute(self::PATTERN))); $formatPattern = $numberFormatElement->getElementsByTagName(self::FORMAT); if ($formatPattern->length != 1) { $countryId = strlen($metadata->getId()) > 0 ? $metadata->getId() : $metadata->getCountryCode(); throw new \RuntimeException('Invalid number of format patterns for country: ' . $countryId); } $nationalFormat = $formatPattern->item(0)->firstChild->nodeValue; $format->setFormat($nationalFormat); }
php
public static function loadNationalFormat( PhoneMetadata $metadata, \DOMElement $numberFormatElement, NumberFormat $format ) { self::setLeadingDigitsPatterns($numberFormatElement, $format); $format->setPattern(self::validateRE($numberFormatElement->getAttribute(self::PATTERN))); $formatPattern = $numberFormatElement->getElementsByTagName(self::FORMAT); if ($formatPattern->length != 1) { $countryId = strlen($metadata->getId()) > 0 ? $metadata->getId() : $metadata->getCountryCode(); throw new \RuntimeException('Invalid number of format patterns for country: ' . $countryId); } $nationalFormat = $formatPattern->item(0)->firstChild->nodeValue; $format->setFormat($nationalFormat); }
[ "public", "static", "function", "loadNationalFormat", "(", "PhoneMetadata", "$", "metadata", ",", "\\", "DOMElement", "$", "numberFormatElement", ",", "NumberFormat", "$", "format", ")", "{", "self", "::", "setLeadingDigitsPatterns", "(", "$", "numberFormatElement", ",", "$", "format", ")", ";", "$", "format", "->", "setPattern", "(", "self", "::", "validateRE", "(", "$", "numberFormatElement", "->", "getAttribute", "(", "self", "::", "PATTERN", ")", ")", ")", ";", "$", "formatPattern", "=", "$", "numberFormatElement", "->", "getElementsByTagName", "(", "self", "::", "FORMAT", ")", ";", "if", "(", "$", "formatPattern", "->", "length", "!=", "1", ")", "{", "$", "countryId", "=", "strlen", "(", "$", "metadata", "->", "getId", "(", ")", ")", ">", "0", "?", "$", "metadata", "->", "getId", "(", ")", ":", "$", "metadata", "->", "getCountryCode", "(", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "'Invalid number of format patterns for country: '", ".", "$", "countryId", ")", ";", "}", "$", "nationalFormat", "=", "$", "formatPattern", "->", "item", "(", "0", ")", "->", "firstChild", "->", "nodeValue", ";", "$", "format", "->", "setFormat", "(", "$", "nationalFormat", ")", ";", "}" ]
Extracts the pattern for the national format. @internal @param PhoneMetadata $metadata @param \DOMElement $numberFormatElement @param NumberFormat $format @throws \RuntimeException if multiple or no formats have been encountered.
[ "Extracts", "the", "pattern", "for", "the", "national", "format", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/BuildMetadataFromXml.php#L341-L356
train
giggsey/libphonenumber-for-php
build/BuildMetadataFromXml.php
BuildMetadataFromXml.loadInternationalFormat
public static function loadInternationalFormat( PhoneMetadata $metadata, \DOMElement $numberFormatElement, NumberFormat $nationalFormat ) { $intlFormat = new NumberFormat(); $intlFormatPattern = $numberFormatElement->getElementsByTagName(self::INTL_FORMAT); $hasExplicitIntlFormatDefined = false; if ($intlFormatPattern->length > 1) { $countryId = strlen($metadata->getId()) > 0 ? $metadata->getId() : $metadata->getCountryCode(); throw new \RuntimeException('Invalid number of intlFormat patterns for country: ' . $countryId); } if ($intlFormatPattern->length == 0) { // Default to use the same as the national pattern if none is defined. $intlFormat->mergeFrom($nationalFormat); } else { $intlFormat->setPattern($numberFormatElement->getAttribute(self::PATTERN)); self::setLeadingDigitsPatterns($numberFormatElement, $intlFormat); $intlFormatPatternValue = $intlFormatPattern->item(0)->firstChild->nodeValue; if ($intlFormatPatternValue !== 'NA') { $intlFormat->setFormat($intlFormatPatternValue); } $hasExplicitIntlFormatDefined = true; } if ($intlFormat->hasFormat()) { $metadata->addIntlNumberFormat($intlFormat); } return $hasExplicitIntlFormatDefined; }
php
public static function loadInternationalFormat( PhoneMetadata $metadata, \DOMElement $numberFormatElement, NumberFormat $nationalFormat ) { $intlFormat = new NumberFormat(); $intlFormatPattern = $numberFormatElement->getElementsByTagName(self::INTL_FORMAT); $hasExplicitIntlFormatDefined = false; if ($intlFormatPattern->length > 1) { $countryId = strlen($metadata->getId()) > 0 ? $metadata->getId() : $metadata->getCountryCode(); throw new \RuntimeException('Invalid number of intlFormat patterns for country: ' . $countryId); } if ($intlFormatPattern->length == 0) { // Default to use the same as the national pattern if none is defined. $intlFormat->mergeFrom($nationalFormat); } else { $intlFormat->setPattern($numberFormatElement->getAttribute(self::PATTERN)); self::setLeadingDigitsPatterns($numberFormatElement, $intlFormat); $intlFormatPatternValue = $intlFormatPattern->item(0)->firstChild->nodeValue; if ($intlFormatPatternValue !== 'NA') { $intlFormat->setFormat($intlFormatPatternValue); } $hasExplicitIntlFormatDefined = true; } if ($intlFormat->hasFormat()) { $metadata->addIntlNumberFormat($intlFormat); } return $hasExplicitIntlFormatDefined; }
[ "public", "static", "function", "loadInternationalFormat", "(", "PhoneMetadata", "$", "metadata", ",", "\\", "DOMElement", "$", "numberFormatElement", ",", "NumberFormat", "$", "nationalFormat", ")", "{", "$", "intlFormat", "=", "new", "NumberFormat", "(", ")", ";", "$", "intlFormatPattern", "=", "$", "numberFormatElement", "->", "getElementsByTagName", "(", "self", "::", "INTL_FORMAT", ")", ";", "$", "hasExplicitIntlFormatDefined", "=", "false", ";", "if", "(", "$", "intlFormatPattern", "->", "length", ">", "1", ")", "{", "$", "countryId", "=", "strlen", "(", "$", "metadata", "->", "getId", "(", ")", ")", ">", "0", "?", "$", "metadata", "->", "getId", "(", ")", ":", "$", "metadata", "->", "getCountryCode", "(", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "'Invalid number of intlFormat patterns for country: '", ".", "$", "countryId", ")", ";", "}", "if", "(", "$", "intlFormatPattern", "->", "length", "==", "0", ")", "{", "// Default to use the same as the national pattern if none is defined.", "$", "intlFormat", "->", "mergeFrom", "(", "$", "nationalFormat", ")", ";", "}", "else", "{", "$", "intlFormat", "->", "setPattern", "(", "$", "numberFormatElement", "->", "getAttribute", "(", "self", "::", "PATTERN", ")", ")", ";", "self", "::", "setLeadingDigitsPatterns", "(", "$", "numberFormatElement", ",", "$", "intlFormat", ")", ";", "$", "intlFormatPatternValue", "=", "$", "intlFormatPattern", "->", "item", "(", "0", ")", "->", "firstChild", "->", "nodeValue", ";", "if", "(", "$", "intlFormatPatternValue", "!==", "'NA'", ")", "{", "$", "intlFormat", "->", "setFormat", "(", "$", "intlFormatPatternValue", ")", ";", "}", "$", "hasExplicitIntlFormatDefined", "=", "true", ";", "}", "if", "(", "$", "intlFormat", "->", "hasFormat", "(", ")", ")", "{", "$", "metadata", "->", "addIntlNumberFormat", "(", "$", "intlFormat", ")", ";", "}", "return", "$", "hasExplicitIntlFormatDefined", ";", "}" ]
Extracts the pattern for international format. If there is no intlFormat, default to using the national format. If the intlFormat is set to "NA" the intlFormat should be ignored. @internal @param PhoneMetadata $metadata @param \DOMElement $numberFormatElement @param NumberFormat $nationalFormat @throws \RuntimeException if multiple intlFormats have been encountered. @return bool whether an international number format is defined.
[ "Extracts", "the", "pattern", "for", "international", "format", ".", "If", "there", "is", "no", "intlFormat", "default", "to", "using", "the", "national", "format", ".", "If", "the", "intlFormat", "is", "set", "to", "NA", "the", "intlFormat", "should", "be", "ignored", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/BuildMetadataFromXml.php#L385-L416
train
giggsey/libphonenumber-for-php
build/BuildMetadataFromXml.php
BuildMetadataFromXml.parsePossibleLengthStringToSet
private static function parsePossibleLengthStringToSet($possibleLengthString) { if (strlen($possibleLengthString) === 0) { throw new \RuntimeException('Empty possibleLength string found.'); } $lengths = explode(',', $possibleLengthString); $lengthSet = array(); $lengthLength = count($lengths); for ($i = 0; $i < $lengthLength; $i++) { $lengthSubstring = $lengths[$i]; if (strlen($lengthSubstring) === 0) { throw new \RuntimeException('Leading, trailing or adjacent commas in possible ' . "length string {$possibleLengthString}, these should only separate numbers or ranges."); } if (substr($lengthSubstring, 0, 1) === '[') { if (substr($lengthSubstring, -1) !== ']') { throw new \RuntimeException("Missing end of range character in possible length string {$possibleLengthString}."); } // Strip the leading and trailing [], and split on the -. $minMax = explode('-', substr($lengthSubstring, 1, -1)); if (count($minMax) !== 2) { throw new \RuntimeException("Ranges must have exactly one - character: missing for {$possibleLengthString}."); } $min = (int)$minMax[0]; $max = (int)$minMax[1]; // We don't even accept [6-7] since we prefer the shorter 6,7 variant; for a range to be in // use the hyphen needs to replace at least one digit. if ($max - $min < 2) { throw new \RuntimeException("The first number in a range should be two or more digits lower than the second. Culprit possibleLength string: {$possibleLengthString}."); } for ($j = $min; $j <= $max; $j++) { if (in_array($j, $lengthSet)) { throw new \RuntimeException("Duplicate length element found ({$j}) in possibleLength string {$possibleLengthString}."); } $lengthSet[] = $j; } } else { $length = $lengthSubstring; if (in_array($length, $lengthSet)) { throw new \RuntimeException("Duplicate length element found ({$length}) in possibleLength string {$possibleLengthString}."); } if (!is_numeric($length)) { throw new \RuntimeException("For input string \"{$length}\""); } $lengthSet[] = (int)$length; } } return $lengthSet; }
php
private static function parsePossibleLengthStringToSet($possibleLengthString) { if (strlen($possibleLengthString) === 0) { throw new \RuntimeException('Empty possibleLength string found.'); } $lengths = explode(',', $possibleLengthString); $lengthSet = array(); $lengthLength = count($lengths); for ($i = 0; $i < $lengthLength; $i++) { $lengthSubstring = $lengths[$i]; if (strlen($lengthSubstring) === 0) { throw new \RuntimeException('Leading, trailing or adjacent commas in possible ' . "length string {$possibleLengthString}, these should only separate numbers or ranges."); } if (substr($lengthSubstring, 0, 1) === '[') { if (substr($lengthSubstring, -1) !== ']') { throw new \RuntimeException("Missing end of range character in possible length string {$possibleLengthString}."); } // Strip the leading and trailing [], and split on the -. $minMax = explode('-', substr($lengthSubstring, 1, -1)); if (count($minMax) !== 2) { throw new \RuntimeException("Ranges must have exactly one - character: missing for {$possibleLengthString}."); } $min = (int)$minMax[0]; $max = (int)$minMax[1]; // We don't even accept [6-7] since we prefer the shorter 6,7 variant; for a range to be in // use the hyphen needs to replace at least one digit. if ($max - $min < 2) { throw new \RuntimeException("The first number in a range should be two or more digits lower than the second. Culprit possibleLength string: {$possibleLengthString}."); } for ($j = $min; $j <= $max; $j++) { if (in_array($j, $lengthSet)) { throw new \RuntimeException("Duplicate length element found ({$j}) in possibleLength string {$possibleLengthString}."); } $lengthSet[] = $j; } } else { $length = $lengthSubstring; if (in_array($length, $lengthSet)) { throw new \RuntimeException("Duplicate length element found ({$length}) in possibleLength string {$possibleLengthString}."); } if (!is_numeric($length)) { throw new \RuntimeException("For input string \"{$length}\""); } $lengthSet[] = (int)$length; } } return $lengthSet; }
[ "private", "static", "function", "parsePossibleLengthStringToSet", "(", "$", "possibleLengthString", ")", "{", "if", "(", "strlen", "(", "$", "possibleLengthString", ")", "===", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Empty possibleLength string found.'", ")", ";", "}", "$", "lengths", "=", "explode", "(", "','", ",", "$", "possibleLengthString", ")", ";", "$", "lengthSet", "=", "array", "(", ")", ";", "$", "lengthLength", "=", "count", "(", "$", "lengths", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "lengthLength", ";", "$", "i", "++", ")", "{", "$", "lengthSubstring", "=", "$", "lengths", "[", "$", "i", "]", ";", "if", "(", "strlen", "(", "$", "lengthSubstring", ")", "===", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Leading, trailing or adjacent commas in possible '", ".", "\"length string {$possibleLengthString}, these should only separate numbers or ranges.\"", ")", ";", "}", "if", "(", "substr", "(", "$", "lengthSubstring", ",", "0", ",", "1", ")", "===", "'['", ")", "{", "if", "(", "substr", "(", "$", "lengthSubstring", ",", "-", "1", ")", "!==", "']'", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Missing end of range character in possible length string {$possibleLengthString}.\"", ")", ";", "}", "// Strip the leading and trailing [], and split on the -.", "$", "minMax", "=", "explode", "(", "'-'", ",", "substr", "(", "$", "lengthSubstring", ",", "1", ",", "-", "1", ")", ")", ";", "if", "(", "count", "(", "$", "minMax", ")", "!==", "2", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Ranges must have exactly one - character: missing for {$possibleLengthString}.\"", ")", ";", "}", "$", "min", "=", "(", "int", ")", "$", "minMax", "[", "0", "]", ";", "$", "max", "=", "(", "int", ")", "$", "minMax", "[", "1", "]", ";", "// We don't even accept [6-7] since we prefer the shorter 6,7 variant; for a range to be in", "// use the hyphen needs to replace at least one digit.", "if", "(", "$", "max", "-", "$", "min", "<", "2", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"The first number in a range should be two or more digits lower than the second. Culprit possibleLength string: {$possibleLengthString}.\"", ")", ";", "}", "for", "(", "$", "j", "=", "$", "min", ";", "$", "j", "<=", "$", "max", ";", "$", "j", "++", ")", "{", "if", "(", "in_array", "(", "$", "j", ",", "$", "lengthSet", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Duplicate length element found ({$j}) in possibleLength string {$possibleLengthString}.\"", ")", ";", "}", "$", "lengthSet", "[", "]", "=", "$", "j", ";", "}", "}", "else", "{", "$", "length", "=", "$", "lengthSubstring", ";", "if", "(", "in_array", "(", "$", "length", ",", "$", "lengthSet", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Duplicate length element found ({$length}) in possibleLength string {$possibleLengthString}.\"", ")", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "length", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"For input string \\\"{$length}\\\"\"", ")", ";", "}", "$", "lengthSet", "[", "]", "=", "(", "int", ")", "$", "length", ";", "}", "}", "return", "$", "lengthSet", ";", "}" ]
Parses a possible length string into a set of the integers that are covered. @param string $possibleLengthString a string specifying the possible lengths of phone numbers. Follows this syntax: ranges or elements are separated by commas, and ranges are specified in [min-max] notation, inclusive. For example, [3-5],7,9,[11-14] should be parsed to 3,4,5,7,9,11,12,13,14 @return array
[ "Parses", "a", "possible", "length", "string", "into", "a", "set", "of", "the", "integers", "that", "are", "covered", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/BuildMetadataFromXml.php#L469-L522
train
giggsey/libphonenumber-for-php
build/BuildMetadataFromXml.php
BuildMetadataFromXml.setPossibleLengthsGeneralDesc
public static function setPossibleLengthsGeneralDesc(PhoneNumberDesc $generalDesc, $metadataId, \DOMElement $data, $isShortNumberMetadata) { $lengths = array(); $localOnlyLengths = array(); // The general description node should *always* be present if metadata for other types is // present, aside from in some unit tests. // (However, for e.g. formatting metadata in PhoneNumberAlternateFormats, no PhoneNumberDesc // elements are present). $generalDescNodes = $data->getElementsByTagName(self::GENERAL_DESC); if ($generalDescNodes->length > 0) { $generalDescNode = $generalDescNodes->item(0); self::populatePossibleLengthSets($generalDescNode, $lengths, $localOnlyLengths); if (count($lengths) > 0 || count($localOnlyLengths) > 0) { // We shouldn't have anything specified at the "general desc" level: we are going to // calculate this ourselves from child elements. throw new \RuntimeException("Found possible lengths specified at general desc: this should be derived from child elements. Affected country: {$metadataId}"); } } if (!$isShortNumberMetadata) { // Make a copy here since we want to remove some nodes, but we don't want to do that on our // actual data. /** @var \DOMElement $allDescData */ $allDescData = $data->cloneNode(true); foreach (self::$phoneNumberDescsWithoutMatchingTypes as $tag) { $nodesToRemove = $allDescData->getElementsByTagName($tag); if ($nodesToRemove->length > 0) { // We check when we process phone number descriptions that there are only one of each // type, so this is safe to do. $allDescData->removeChild($nodesToRemove->item(0)); } } self::populatePossibleLengthSets($allDescData, $lengths, $localOnlyLengths); } else { // For short number metadata, we want to copy the lengths from the "short code" section only. // This is because it's the more detailed validation pattern, it's not a sub-type of short // codes. The other lengths will be checked later to see that they are a sub-set of these // possible lengths. $shortCodeDescList = $data->getElementsByTagName(self::SHORT_CODE); if (count($shortCodeDescList) > 0) { $shortCodeDesc = $shortCodeDescList->item(0); self::populatePossibleLengthSets($shortCodeDesc, $lengths, $localOnlyLengths); } if (count($localOnlyLengths) > 0) { throw new \RuntimeException('Found local-only lengths in short-number metadata'); } } self::setPossibleLengths($lengths, $localOnlyLengths, null, $generalDesc); }
php
public static function setPossibleLengthsGeneralDesc(PhoneNumberDesc $generalDesc, $metadataId, \DOMElement $data, $isShortNumberMetadata) { $lengths = array(); $localOnlyLengths = array(); // The general description node should *always* be present if metadata for other types is // present, aside from in some unit tests. // (However, for e.g. formatting metadata in PhoneNumberAlternateFormats, no PhoneNumberDesc // elements are present). $generalDescNodes = $data->getElementsByTagName(self::GENERAL_DESC); if ($generalDescNodes->length > 0) { $generalDescNode = $generalDescNodes->item(0); self::populatePossibleLengthSets($generalDescNode, $lengths, $localOnlyLengths); if (count($lengths) > 0 || count($localOnlyLengths) > 0) { // We shouldn't have anything specified at the "general desc" level: we are going to // calculate this ourselves from child elements. throw new \RuntimeException("Found possible lengths specified at general desc: this should be derived from child elements. Affected country: {$metadataId}"); } } if (!$isShortNumberMetadata) { // Make a copy here since we want to remove some nodes, but we don't want to do that on our // actual data. /** @var \DOMElement $allDescData */ $allDescData = $data->cloneNode(true); foreach (self::$phoneNumberDescsWithoutMatchingTypes as $tag) { $nodesToRemove = $allDescData->getElementsByTagName($tag); if ($nodesToRemove->length > 0) { // We check when we process phone number descriptions that there are only one of each // type, so this is safe to do. $allDescData->removeChild($nodesToRemove->item(0)); } } self::populatePossibleLengthSets($allDescData, $lengths, $localOnlyLengths); } else { // For short number metadata, we want to copy the lengths from the "short code" section only. // This is because it's the more detailed validation pattern, it's not a sub-type of short // codes. The other lengths will be checked later to see that they are a sub-set of these // possible lengths. $shortCodeDescList = $data->getElementsByTagName(self::SHORT_CODE); if (count($shortCodeDescList) > 0) { $shortCodeDesc = $shortCodeDescList->item(0); self::populatePossibleLengthSets($shortCodeDesc, $lengths, $localOnlyLengths); } if (count($localOnlyLengths) > 0) { throw new \RuntimeException('Found local-only lengths in short-number metadata'); } } self::setPossibleLengths($lengths, $localOnlyLengths, null, $generalDesc); }
[ "public", "static", "function", "setPossibleLengthsGeneralDesc", "(", "PhoneNumberDesc", "$", "generalDesc", ",", "$", "metadataId", ",", "\\", "DOMElement", "$", "data", ",", "$", "isShortNumberMetadata", ")", "{", "$", "lengths", "=", "array", "(", ")", ";", "$", "localOnlyLengths", "=", "array", "(", ")", ";", "// The general description node should *always* be present if metadata for other types is", "// present, aside from in some unit tests.", "// (However, for e.g. formatting metadata in PhoneNumberAlternateFormats, no PhoneNumberDesc", "// elements are present).", "$", "generalDescNodes", "=", "$", "data", "->", "getElementsByTagName", "(", "self", "::", "GENERAL_DESC", ")", ";", "if", "(", "$", "generalDescNodes", "->", "length", ">", "0", ")", "{", "$", "generalDescNode", "=", "$", "generalDescNodes", "->", "item", "(", "0", ")", ";", "self", "::", "populatePossibleLengthSets", "(", "$", "generalDescNode", ",", "$", "lengths", ",", "$", "localOnlyLengths", ")", ";", "if", "(", "count", "(", "$", "lengths", ")", ">", "0", "||", "count", "(", "$", "localOnlyLengths", ")", ">", "0", ")", "{", "// We shouldn't have anything specified at the \"general desc\" level: we are going to", "// calculate this ourselves from child elements.", "throw", "new", "\\", "RuntimeException", "(", "\"Found possible lengths specified at general desc: this should be derived from child elements. Affected country: {$metadataId}\"", ")", ";", "}", "}", "if", "(", "!", "$", "isShortNumberMetadata", ")", "{", "// Make a copy here since we want to remove some nodes, but we don't want to do that on our", "// actual data.", "/** @var \\DOMElement $allDescData */", "$", "allDescData", "=", "$", "data", "->", "cloneNode", "(", "true", ")", ";", "foreach", "(", "self", "::", "$", "phoneNumberDescsWithoutMatchingTypes", "as", "$", "tag", ")", "{", "$", "nodesToRemove", "=", "$", "allDescData", "->", "getElementsByTagName", "(", "$", "tag", ")", ";", "if", "(", "$", "nodesToRemove", "->", "length", ">", "0", ")", "{", "// We check when we process phone number descriptions that there are only one of each", "// type, so this is safe to do.", "$", "allDescData", "->", "removeChild", "(", "$", "nodesToRemove", "->", "item", "(", "0", ")", ")", ";", "}", "}", "self", "::", "populatePossibleLengthSets", "(", "$", "allDescData", ",", "$", "lengths", ",", "$", "localOnlyLengths", ")", ";", "}", "else", "{", "// For short number metadata, we want to copy the lengths from the \"short code\" section only.", "// This is because it's the more detailed validation pattern, it's not a sub-type of short", "// codes. The other lengths will be checked later to see that they are a sub-set of these", "// possible lengths.", "$", "shortCodeDescList", "=", "$", "data", "->", "getElementsByTagName", "(", "self", "::", "SHORT_CODE", ")", ";", "if", "(", "count", "(", "$", "shortCodeDescList", ")", ">", "0", ")", "{", "$", "shortCodeDesc", "=", "$", "shortCodeDescList", "->", "item", "(", "0", ")", ";", "self", "::", "populatePossibleLengthSets", "(", "$", "shortCodeDesc", ",", "$", "lengths", ",", "$", "localOnlyLengths", ")", ";", "}", "if", "(", "count", "(", "$", "localOnlyLengths", ")", ">", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Found local-only lengths in short-number metadata'", ")", ";", "}", "}", "self", "::", "setPossibleLengths", "(", "$", "lengths", ",", "$", "localOnlyLengths", ",", "null", ",", "$", "generalDesc", ")", ";", "}" ]
Sets possible lengths in the general description, derived from certain child elements @internal @param PhoneNumberDesc $generalDesc @param string $metadataId @param \DOMElement $data @param bool $isShortNumberMetadata
[ "Sets", "possible", "lengths", "in", "the", "general", "description", "derived", "from", "certain", "child", "elements" ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/BuildMetadataFromXml.php#L577-L624
train
giggsey/libphonenumber-for-php
build/BuildMetadataFromXml.php
BuildMetadataFromXml.setPossibleLengths
private static function setPossibleLengths($lengths, $localOnlyLengths, PhoneNumberDesc $parentDesc = null, PhoneNumberDesc $desc) { // We clear these fields since the metadata tends to inherit from the parent element for other // fields (via a mergeFrom). $desc->clearPossibleLength(); $desc->clearPossibleLengthLocalOnly(); // Only add the lengths to this sub-type if they aren't exactly the same as the possible // lengths in the general desc (for metadata size reasons). if ($parentDesc === null || !self::arePossibleLengthsEqual($lengths, $parentDesc)) { foreach ($lengths as $length) { if ($parentDesc === null || in_array($length, $parentDesc->getPossibleLength())) { $desc->addPossibleLength($length); } else { // We shouldn't have possible lengths defined in a child element that are not covered by // the general description. We check this here even though the general description is // derived from child elements because it is only derived from a subset, and we need to // ensure *all* child elements have a valid possible length. throw new \RuntimeException("Out-of-range possible length found ({$length}), parent lengths " . implode(',', $parentDesc->getPossibleLength())); } } } // We check that the local-only length isn't also a normal possible length (only relevant for // the general-desc, since within elements such as fixed-line we would throw an exception if we // saw this) before adding it to the collection of possible local-only lengths. foreach ($localOnlyLengths as $length) { if (!in_array($length, $lengths)) { // We check it is covered by either of the possible length sets of the parent // PhoneNumberDesc, because for example 7 might be a valid localOnly length for mobile, but // a valid national length for fixedLine, so the generalDesc would have the 7 removed from // localOnly. if ($parentDesc === null || in_array($length, $parentDesc->getPossibleLength()) || in_array($length, $parentDesc->getPossibleLengthLocalOnly()) ) { $desc->addPossibleLengthLocalOnly($length); } else { throw new \RuntimeException("Out-of-range local-only possible length found ({$length}), parent length {$parentDesc->getPossibleLengthLocalOnly()}"); } } } }
php
private static function setPossibleLengths($lengths, $localOnlyLengths, PhoneNumberDesc $parentDesc = null, PhoneNumberDesc $desc) { // We clear these fields since the metadata tends to inherit from the parent element for other // fields (via a mergeFrom). $desc->clearPossibleLength(); $desc->clearPossibleLengthLocalOnly(); // Only add the lengths to this sub-type if they aren't exactly the same as the possible // lengths in the general desc (for metadata size reasons). if ($parentDesc === null || !self::arePossibleLengthsEqual($lengths, $parentDesc)) { foreach ($lengths as $length) { if ($parentDesc === null || in_array($length, $parentDesc->getPossibleLength())) { $desc->addPossibleLength($length); } else { // We shouldn't have possible lengths defined in a child element that are not covered by // the general description. We check this here even though the general description is // derived from child elements because it is only derived from a subset, and we need to // ensure *all* child elements have a valid possible length. throw new \RuntimeException("Out-of-range possible length found ({$length}), parent lengths " . implode(',', $parentDesc->getPossibleLength())); } } } // We check that the local-only length isn't also a normal possible length (only relevant for // the general-desc, since within elements such as fixed-line we would throw an exception if we // saw this) before adding it to the collection of possible local-only lengths. foreach ($localOnlyLengths as $length) { if (!in_array($length, $lengths)) { // We check it is covered by either of the possible length sets of the parent // PhoneNumberDesc, because for example 7 might be a valid localOnly length for mobile, but // a valid national length for fixedLine, so the generalDesc would have the 7 removed from // localOnly. if ($parentDesc === null || in_array($length, $parentDesc->getPossibleLength()) || in_array($length, $parentDesc->getPossibleLengthLocalOnly()) ) { $desc->addPossibleLengthLocalOnly($length); } else { throw new \RuntimeException("Out-of-range local-only possible length found ({$length}), parent length {$parentDesc->getPossibleLengthLocalOnly()}"); } } } }
[ "private", "static", "function", "setPossibleLengths", "(", "$", "lengths", ",", "$", "localOnlyLengths", ",", "PhoneNumberDesc", "$", "parentDesc", "=", "null", ",", "PhoneNumberDesc", "$", "desc", ")", "{", "// We clear these fields since the metadata tends to inherit from the parent element for other", "// fields (via a mergeFrom).", "$", "desc", "->", "clearPossibleLength", "(", ")", ";", "$", "desc", "->", "clearPossibleLengthLocalOnly", "(", ")", ";", "// Only add the lengths to this sub-type if they aren't exactly the same as the possible", "// lengths in the general desc (for metadata size reasons).", "if", "(", "$", "parentDesc", "===", "null", "||", "!", "self", "::", "arePossibleLengthsEqual", "(", "$", "lengths", ",", "$", "parentDesc", ")", ")", "{", "foreach", "(", "$", "lengths", "as", "$", "length", ")", "{", "if", "(", "$", "parentDesc", "===", "null", "||", "in_array", "(", "$", "length", ",", "$", "parentDesc", "->", "getPossibleLength", "(", ")", ")", ")", "{", "$", "desc", "->", "addPossibleLength", "(", "$", "length", ")", ";", "}", "else", "{", "// We shouldn't have possible lengths defined in a child element that are not covered by", "// the general description. We check this here even though the general description is", "// derived from child elements because it is only derived from a subset, and we need to", "// ensure *all* child elements have a valid possible length.", "throw", "new", "\\", "RuntimeException", "(", "\"Out-of-range possible length found ({$length}), parent lengths \"", ".", "implode", "(", "','", ",", "$", "parentDesc", "->", "getPossibleLength", "(", ")", ")", ")", ";", "}", "}", "}", "// We check that the local-only length isn't also a normal possible length (only relevant for", "// the general-desc, since within elements such as fixed-line we would throw an exception if we", "// saw this) before adding it to the collection of possible local-only lengths.", "foreach", "(", "$", "localOnlyLengths", "as", "$", "length", ")", "{", "if", "(", "!", "in_array", "(", "$", "length", ",", "$", "lengths", ")", ")", "{", "// We check it is covered by either of the possible length sets of the parent", "// PhoneNumberDesc, because for example 7 might be a valid localOnly length for mobile, but", "// a valid national length for fixedLine, so the generalDesc would have the 7 removed from", "// localOnly.", "if", "(", "$", "parentDesc", "===", "null", "||", "in_array", "(", "$", "length", ",", "$", "parentDesc", "->", "getPossibleLength", "(", ")", ")", "||", "in_array", "(", "$", "length", ",", "$", "parentDesc", "->", "getPossibleLengthLocalOnly", "(", ")", ")", ")", "{", "$", "desc", "->", "addPossibleLengthLocalOnly", "(", "$", "length", ")", ";", "}", "else", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Out-of-range local-only possible length found ({$length}), parent length {$parentDesc->getPossibleLengthLocalOnly()}\"", ")", ";", "}", "}", "}", "}" ]
Sets the possible length fields in the metadata from the sets of data passed in. Checks that the length is covered by the "parent" phone number description element if one is present, and if the lengths are exactly the same as this, they are not filled in for efficiency reasons. @param array $lengths @param array $localOnlyLengths @param PhoneNumberDesc $parentDesc @param PhoneNumberDesc $desc
[ "Sets", "the", "possible", "length", "fields", "in", "the", "metadata", "from", "the", "sets", "of", "data", "passed", "in", ".", "Checks", "that", "the", "length", "is", "covered", "by", "the", "parent", "phone", "number", "description", "element", "if", "one", "is", "present", "and", "if", "the", "lengths", "are", "exactly", "the", "same", "as", "this", "they", "are", "not", "filled", "in", "for", "efficiency", "reasons", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/BuildMetadataFromXml.php#L636-L677
train
giggsey/libphonenumber-for-php
build/GeneratePhonePrefixData.php
GeneratePhonePrefixData.parseTextFile
private function parseTextFile($filePath, \Closure $handler) { if (!file_exists($filePath) || !is_readable($filePath)) { throw new \InvalidArgumentException("File '{$filePath}' does not exist"); } $data = file($filePath); $countryData = array(); foreach ($data as $line) { // Remove \n $line = str_replace(array("\n", "\r"), '', $line); $line = trim($line); if (strlen($line) == 0 || substr($line, 0, 1) == '#') { continue; } if (strpos($line, '|')) { // Valid line $parts = explode('|', $line); $prefix = $parts[0]; $location = $parts[1]; $handler($prefix, $location); } } return $countryData; }
php
private function parseTextFile($filePath, \Closure $handler) { if (!file_exists($filePath) || !is_readable($filePath)) { throw new \InvalidArgumentException("File '{$filePath}' does not exist"); } $data = file($filePath); $countryData = array(); foreach ($data as $line) { // Remove \n $line = str_replace(array("\n", "\r"), '', $line); $line = trim($line); if (strlen($line) == 0 || substr($line, 0, 1) == '#') { continue; } if (strpos($line, '|')) { // Valid line $parts = explode('|', $line); $prefix = $parts[0]; $location = $parts[1]; $handler($prefix, $location); } } return $countryData; }
[ "private", "function", "parseTextFile", "(", "$", "filePath", ",", "\\", "Closure", "$", "handler", ")", "{", "if", "(", "!", "file_exists", "(", "$", "filePath", ")", "||", "!", "is_readable", "(", "$", "filePath", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"File '{$filePath}' does not exist\"", ")", ";", "}", "$", "data", "=", "file", "(", "$", "filePath", ")", ";", "$", "countryData", "=", "array", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "line", ")", "{", "// Remove \\n", "$", "line", "=", "str_replace", "(", "array", "(", "\"\\n\"", ",", "\"\\r\"", ")", ",", "''", ",", "$", "line", ")", ";", "$", "line", "=", "trim", "(", "$", "line", ")", ";", "if", "(", "strlen", "(", "$", "line", ")", "==", "0", "||", "substr", "(", "$", "line", ",", "0", ",", "1", ")", "==", "'#'", ")", "{", "continue", ";", "}", "if", "(", "strpos", "(", "$", "line", ",", "'|'", ")", ")", "{", "// Valid line", "$", "parts", "=", "explode", "(", "'|'", ",", "$", "line", ")", ";", "$", "prefix", "=", "$", "parts", "[", "0", "]", ";", "$", "location", "=", "$", "parts", "[", "1", "]", ";", "$", "handler", "(", "$", "prefix", ",", "$", "location", ")", ";", "}", "}", "return", "$", "countryData", ";", "}" ]
Reads phone prefix data from the provides file path and invokes the given handler for each mapping read. @param string $filePath @param \Closure $handler @return array @throws \InvalidArgumentException
[ "Reads", "phone", "prefix", "data", "from", "the", "provides", "file", "path", "and", "invokes", "the", "given", "handler", "for", "each", "mapping", "read", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/GeneratePhonePrefixData.php#L183-L214
train
giggsey/libphonenumber-for-php
build/GeneratePhonePrefixData.php
GeneratePhonePrefixData.makeDataFallbackToEnglish
private function makeDataFallbackToEnglish($textFile, &$mappings) { $englishPath = $this->getEnglishDataPath($textFile); if ($textFile == $englishPath || !file_exists($this->getFilePath($englishPath))) { return; } $countryCode = substr($textFile, 3, 2); if (!array_key_exists($countryCode, $this->englishMaps)) { $englishMap = $this->readMappingsFromFile($englishPath); $this->englishMaps[$countryCode] = $englishMap; } $this->compressAccordingToEnglishData($this->englishMaps[$countryCode], $mappings); }
php
private function makeDataFallbackToEnglish($textFile, &$mappings) { $englishPath = $this->getEnglishDataPath($textFile); if ($textFile == $englishPath || !file_exists($this->getFilePath($englishPath))) { return; } $countryCode = substr($textFile, 3, 2); if (!array_key_exists($countryCode, $this->englishMaps)) { $englishMap = $this->readMappingsFromFile($englishPath); $this->englishMaps[$countryCode] = $englishMap; } $this->compressAccordingToEnglishData($this->englishMaps[$countryCode], $mappings); }
[ "private", "function", "makeDataFallbackToEnglish", "(", "$", "textFile", ",", "&", "$", "mappings", ")", "{", "$", "englishPath", "=", "$", "this", "->", "getEnglishDataPath", "(", "$", "textFile", ")", ";", "if", "(", "$", "textFile", "==", "$", "englishPath", "||", "!", "file_exists", "(", "$", "this", "->", "getFilePath", "(", "$", "englishPath", ")", ")", ")", "{", "return", ";", "}", "$", "countryCode", "=", "substr", "(", "$", "textFile", ",", "3", ",", "2", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "countryCode", ",", "$", "this", "->", "englishMaps", ")", ")", "{", "$", "englishMap", "=", "$", "this", "->", "readMappingsFromFile", "(", "$", "englishPath", ")", ";", "$", "this", "->", "englishMaps", "[", "$", "countryCode", "]", "=", "$", "englishMap", ";", "}", "$", "this", "->", "compressAccordingToEnglishData", "(", "$", "this", "->", "englishMaps", "[", "$", "countryCode", "]", ",", "$", "mappings", ")", ";", "}" ]
Compress the provided mappings according to the English data file if any. @param string $textFile @param array $mappings
[ "Compress", "the", "provided", "mappings", "according", "to", "the", "English", "data", "file", "if", "any", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/GeneratePhonePrefixData.php#L307-L324
train
giggsey/libphonenumber-for-php
build/GeneratePhonePrefixData.php
GeneratePhonePrefixData.getPhonePrefixLanguagePairFromFilename
private function getPhonePrefixLanguagePairFromFilename($outputFile) { $parts = explode(DIRECTORY_SEPARATOR, $outputFile); $returnObj = new \stdClass(); $returnObj->language = $parts[0]; $returnObj->prefix = $this->getCountryCodeFromTextFileName($parts[1]); return $returnObj; }
php
private function getPhonePrefixLanguagePairFromFilename($outputFile) { $parts = explode(DIRECTORY_SEPARATOR, $outputFile); $returnObj = new \stdClass(); $returnObj->language = $parts[0]; $returnObj->prefix = $this->getCountryCodeFromTextFileName($parts[1]); return $returnObj; }
[ "private", "function", "getPhonePrefixLanguagePairFromFilename", "(", "$", "outputFile", ")", "{", "$", "parts", "=", "explode", "(", "DIRECTORY_SEPARATOR", ",", "$", "outputFile", ")", ";", "$", "returnObj", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "returnObj", "->", "language", "=", "$", "parts", "[", "0", "]", ";", "$", "returnObj", "->", "prefix", "=", "$", "this", "->", "getCountryCodeFromTextFileName", "(", "$", "parts", "[", "1", "]", ")", ";", "return", "$", "returnObj", ";", "}" ]
Extracts the phone prefix and the language code contained in the provided file name.
[ "Extracts", "the", "phone", "prefix", "and", "the", "language", "code", "contained", "in", "the", "provided", "file", "name", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/GeneratePhonePrefixData.php#L387-L397
train
giggsey/libphonenumber-for-php
src/PhoneNumberToCarrierMapper.php
PhoneNumberToCarrierMapper.getNameForValidNumber
public function getNameForValidNumber(PhoneNumber $number, $languageCode) { $languageStr = Locale::getPrimaryLanguage($languageCode); $scriptStr = ''; $regionStr = Locale::getRegion($languageCode); return $this->prefixFileReader->getDescriptionForNumber($number, $languageStr, $scriptStr, $regionStr); }
php
public function getNameForValidNumber(PhoneNumber $number, $languageCode) { $languageStr = Locale::getPrimaryLanguage($languageCode); $scriptStr = ''; $regionStr = Locale::getRegion($languageCode); return $this->prefixFileReader->getDescriptionForNumber($number, $languageStr, $scriptStr, $regionStr); }
[ "public", "function", "getNameForValidNumber", "(", "PhoneNumber", "$", "number", ",", "$", "languageCode", ")", "{", "$", "languageStr", "=", "Locale", "::", "getPrimaryLanguage", "(", "$", "languageCode", ")", ";", "$", "scriptStr", "=", "''", ";", "$", "regionStr", "=", "Locale", "::", "getRegion", "(", "$", "languageCode", ")", ";", "return", "$", "this", "->", "prefixFileReader", "->", "getDescriptionForNumber", "(", "$", "number", ",", "$", "languageStr", ",", "$", "scriptStr", ",", "$", "regionStr", ")", ";", "}" ]
Returns a carrier name for the given phone number, in the language provided. The carrier name is the one the number was originally allocated to, however if the country supports mobile number portability the number might not belong to the returned carrier anymore. If no mapping is found an empty string is returned. <p>This method assumes the validity of the number passed in has already been checked, and that the number is suitable for carrier lookup. We consider mobile and pager numbers possible candidates for carrier lookup. @param PhoneNumber $number a valid phone number for which we want to get a carrier name @param string $languageCode the language code in which the name should be written @return string a carrier name for the given phone number
[ "Returns", "a", "carrier", "name", "for", "the", "given", "phone", "number", "in", "the", "language", "provided", ".", "The", "carrier", "name", "is", "the", "one", "the", "number", "was", "originally", "allocated", "to", "however", "if", "the", "country", "supports", "mobile", "number", "portability", "the", "number", "might", "not", "belong", "to", "the", "returned", "carrier", "anymore", ".", "If", "no", "mapping", "is", "found", "an", "empty", "string", "is", "returned", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberToCarrierMapper.php#L71-L78
train
giggsey/libphonenumber-for-php
src/PhoneNumberToCarrierMapper.php
PhoneNumberToCarrierMapper.isMobile
protected function isMobile($numberType) { return ($numberType === PhoneNumberType::MOBILE || $numberType === PhoneNumberType::FIXED_LINE_OR_MOBILE || $numberType === PhoneNumberType::PAGER ); }
php
protected function isMobile($numberType) { return ($numberType === PhoneNumberType::MOBILE || $numberType === PhoneNumberType::FIXED_LINE_OR_MOBILE || $numberType === PhoneNumberType::PAGER ); }
[ "protected", "function", "isMobile", "(", "$", "numberType", ")", "{", "return", "(", "$", "numberType", "===", "PhoneNumberType", "::", "MOBILE", "||", "$", "numberType", "===", "PhoneNumberType", "::", "FIXED_LINE_OR_MOBILE", "||", "$", "numberType", "===", "PhoneNumberType", "::", "PAGER", ")", ";", "}" ]
Checks if the supplied number type supports carrier lookup. @param int $numberType A PhoneNumberType int @return bool
[ "Checks", "if", "the", "supplied", "number", "type", "supports", "carrier", "lookup", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberToCarrierMapper.php#L124-L130
train
giggsey/libphonenumber-for-php
src/ShortNumberInfo.php
ShortNumberInfo.getRegionCodesForCountryCode
protected function getRegionCodesForCountryCode($countryCallingCode) { if (!array_key_exists($countryCallingCode, $this->countryCallingCodeToRegionCodeMap)) { $regionCodes = null; } else { $regionCodes = $this->countryCallingCodeToRegionCodeMap[$countryCallingCode]; } return ($regionCodes === null) ? array() : $regionCodes; }
php
protected function getRegionCodesForCountryCode($countryCallingCode) { if (!array_key_exists($countryCallingCode, $this->countryCallingCodeToRegionCodeMap)) { $regionCodes = null; } else { $regionCodes = $this->countryCallingCodeToRegionCodeMap[$countryCallingCode]; } return ($regionCodes === null) ? array() : $regionCodes; }
[ "protected", "function", "getRegionCodesForCountryCode", "(", "$", "countryCallingCode", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "countryCallingCode", ",", "$", "this", "->", "countryCallingCodeToRegionCodeMap", ")", ")", "{", "$", "regionCodes", "=", "null", ";", "}", "else", "{", "$", "regionCodes", "=", "$", "this", "->", "countryCallingCodeToRegionCodeMap", "[", "$", "countryCallingCode", "]", ";", "}", "return", "(", "$", "regionCodes", "===", "null", ")", "?", "array", "(", ")", ":", "$", "regionCodes", ";", "}" ]
Returns a list with teh region codes that match the specific country calling code. For non-geographical country calling codes, the region code 001 is returned. Also, in the case of no region code being found, an empty list is returned. @param int $countryCallingCode @return array
[ "Returns", "a", "list", "with", "teh", "region", "codes", "that", "match", "the", "specific", "country", "calling", "code", ".", "For", "non", "-", "geographical", "country", "calling", "codes", "the", "region", "code", "001", "is", "returned", ".", "Also", "in", "the", "case", "of", "no", "region", "code", "being", "found", "an", "empty", "list", "is", "returned", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/ShortNumberInfo.php#L75-L84
train
giggsey/libphonenumber-for-php
src/ShortNumberInfo.php
ShortNumberInfo.regionDialingFromMatchesNumber
protected function regionDialingFromMatchesNumber(PhoneNumber $number, $regionDialingFrom) { $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode()); return in_array($regionDialingFrom, $regionCodes); }
php
protected function regionDialingFromMatchesNumber(PhoneNumber $number, $regionDialingFrom) { $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode()); return in_array($regionDialingFrom, $regionCodes); }
[ "protected", "function", "regionDialingFromMatchesNumber", "(", "PhoneNumber", "$", "number", ",", "$", "regionDialingFrom", ")", "{", "$", "regionCodes", "=", "$", "this", "->", "getRegionCodesForCountryCode", "(", "$", "number", "->", "getCountryCode", "(", ")", ")", ";", "return", "in_array", "(", "$", "regionDialingFrom", ",", "$", "regionCodes", ")", ";", "}" ]
Helper method to check that the country calling code of the number matches the region it's being dialed from. @param PhoneNumber $number @param string $regionDialingFrom @return bool
[ "Helper", "method", "to", "check", "that", "the", "country", "calling", "code", "of", "the", "number", "matches", "the", "region", "it", "s", "being", "dialed", "from", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/ShortNumberInfo.php#L93-L98
train
giggsey/libphonenumber-for-php
src/ShortNumberInfo.php
ShortNumberInfo.getExampleShortNumber
public function getExampleShortNumber($regionCode) { $phoneMetadata = $this->getMetadataForRegion($regionCode); if ($phoneMetadata === null) { return ''; } /** @var PhoneNumberDesc $desc */ $desc = $phoneMetadata->getShortCode(); if ($desc !== null && $desc->hasExampleNumber()) { return $desc->getExampleNumber(); } return ''; }
php
public function getExampleShortNumber($regionCode) { $phoneMetadata = $this->getMetadataForRegion($regionCode); if ($phoneMetadata === null) { return ''; } /** @var PhoneNumberDesc $desc */ $desc = $phoneMetadata->getShortCode(); if ($desc !== null && $desc->hasExampleNumber()) { return $desc->getExampleNumber(); } return ''; }
[ "public", "function", "getExampleShortNumber", "(", "$", "regionCode", ")", "{", "$", "phoneMetadata", "=", "$", "this", "->", "getMetadataForRegion", "(", "$", "regionCode", ")", ";", "if", "(", "$", "phoneMetadata", "===", "null", ")", "{", "return", "''", ";", "}", "/** @var PhoneNumberDesc $desc */", "$", "desc", "=", "$", "phoneMetadata", "->", "getShortCode", "(", ")", ";", "if", "(", "$", "desc", "!==", "null", "&&", "$", "desc", "->", "hasExampleNumber", "(", ")", ")", "{", "return", "$", "desc", "->", "getExampleNumber", "(", ")", ";", "}", "return", "''", ";", "}" ]
Gets a valid short number for the specified region. @param $regionCode String the region for which an example short number is needed @return string a valid short number for the specified region. Returns an empty string when the metadata does not contain such information.
[ "Gets", "a", "valid", "short", "number", "for", "the", "specified", "region", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/ShortNumberInfo.php#L112-L125
train
giggsey/libphonenumber-for-php
src/ShortNumberInfo.php
ShortNumberInfo.getExampleShortNumberForCost
public function getExampleShortNumberForCost($regionCode, $cost) { $phoneMetadata = $this->getMetadataForRegion($regionCode); if ($phoneMetadata === null) { return ''; } /** @var PhoneNumberDesc $desc */ $desc = null; switch ($cost) { case ShortNumberCost::TOLL_FREE: $desc = $phoneMetadata->getTollFree(); break; case ShortNumberCost::STANDARD_RATE: $desc = $phoneMetadata->getStandardRate(); break; case ShortNumberCost::PREMIUM_RATE: $desc = $phoneMetadata->getPremiumRate(); break; default: // UNKNOWN_COST numbers are computed by the process of elimination from the other cost categories break; } if ($desc !== null && $desc->hasExampleNumber()) { return $desc->getExampleNumber(); } return ''; }
php
public function getExampleShortNumberForCost($regionCode, $cost) { $phoneMetadata = $this->getMetadataForRegion($regionCode); if ($phoneMetadata === null) { return ''; } /** @var PhoneNumberDesc $desc */ $desc = null; switch ($cost) { case ShortNumberCost::TOLL_FREE: $desc = $phoneMetadata->getTollFree(); break; case ShortNumberCost::STANDARD_RATE: $desc = $phoneMetadata->getStandardRate(); break; case ShortNumberCost::PREMIUM_RATE: $desc = $phoneMetadata->getPremiumRate(); break; default: // UNKNOWN_COST numbers are computed by the process of elimination from the other cost categories break; } if ($desc !== null && $desc->hasExampleNumber()) { return $desc->getExampleNumber(); } return ''; }
[ "public", "function", "getExampleShortNumberForCost", "(", "$", "regionCode", ",", "$", "cost", ")", "{", "$", "phoneMetadata", "=", "$", "this", "->", "getMetadataForRegion", "(", "$", "regionCode", ")", ";", "if", "(", "$", "phoneMetadata", "===", "null", ")", "{", "return", "''", ";", "}", "/** @var PhoneNumberDesc $desc */", "$", "desc", "=", "null", ";", "switch", "(", "$", "cost", ")", "{", "case", "ShortNumberCost", "::", "TOLL_FREE", ":", "$", "desc", "=", "$", "phoneMetadata", "->", "getTollFree", "(", ")", ";", "break", ";", "case", "ShortNumberCost", "::", "STANDARD_RATE", ":", "$", "desc", "=", "$", "phoneMetadata", "->", "getStandardRate", "(", ")", ";", "break", ";", "case", "ShortNumberCost", "::", "PREMIUM_RATE", ":", "$", "desc", "=", "$", "phoneMetadata", "->", "getPremiumRate", "(", ")", ";", "break", ";", "default", ":", "// UNKNOWN_COST numbers are computed by the process of elimination from the other cost categories", "break", ";", "}", "if", "(", "$", "desc", "!==", "null", "&&", "$", "desc", "->", "hasExampleNumber", "(", ")", ")", "{", "return", "$", "desc", "->", "getExampleNumber", "(", ")", ";", "}", "return", "''", ";", "}" ]
Gets a valid short number for the specified cost category. @param string $regionCode the region for which an example short number is needed @param int $cost the cost category of number that is needed @return string a valid short number for the specified region and cost category. Returns an empty string when the metadata does not contain such information, or the cost is UNKNOWN_COST.
[ "Gets", "a", "valid", "short", "number", "for", "the", "specified", "cost", "category", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/ShortNumberInfo.php#L174-L203
train
giggsey/libphonenumber-for-php
src/ShortNumberInfo.php
ShortNumberInfo.getRegionCodeForShortNumberFromRegionList
protected function getRegionCodeForShortNumberFromRegionList(PhoneNumber $number, $regionCodes) { if (count($regionCodes) == 0) { return null; } if (count($regionCodes) == 1) { return $regionCodes[0]; } $nationalNumber = $this->getNationalSignificantNumber($number); foreach ($regionCodes as $regionCode) { $phoneMetadata = $this->getMetadataForRegion($regionCode); if ($phoneMetadata !== null && $this->matchesPossibleNumberAndNationalNumber($nationalNumber, $phoneMetadata->getShortCode()) ) { // The number is valid for this region. return $regionCode; } } return null; }
php
protected function getRegionCodeForShortNumberFromRegionList(PhoneNumber $number, $regionCodes) { if (count($regionCodes) == 0) { return null; } if (count($regionCodes) == 1) { return $regionCodes[0]; } $nationalNumber = $this->getNationalSignificantNumber($number); foreach ($regionCodes as $regionCode) { $phoneMetadata = $this->getMetadataForRegion($regionCode); if ($phoneMetadata !== null && $this->matchesPossibleNumberAndNationalNumber($nationalNumber, $phoneMetadata->getShortCode()) ) { // The number is valid for this region. return $regionCode; } } return null; }
[ "protected", "function", "getRegionCodeForShortNumberFromRegionList", "(", "PhoneNumber", "$", "number", ",", "$", "regionCodes", ")", "{", "if", "(", "count", "(", "$", "regionCodes", ")", "==", "0", ")", "{", "return", "null", ";", "}", "if", "(", "count", "(", "$", "regionCodes", ")", "==", "1", ")", "{", "return", "$", "regionCodes", "[", "0", "]", ";", "}", "$", "nationalNumber", "=", "$", "this", "->", "getNationalSignificantNumber", "(", "$", "number", ")", ";", "foreach", "(", "$", "regionCodes", "as", "$", "regionCode", ")", "{", "$", "phoneMetadata", "=", "$", "this", "->", "getMetadataForRegion", "(", "$", "regionCode", ")", ";", "if", "(", "$", "phoneMetadata", "!==", "null", "&&", "$", "this", "->", "matchesPossibleNumberAndNationalNumber", "(", "$", "nationalNumber", ",", "$", "phoneMetadata", "->", "getShortCode", "(", ")", ")", ")", "{", "// The number is valid for this region.", "return", "$", "regionCode", ";", "}", "}", "return", "null", ";", "}" ]
Helper method to get the region code for a given phone number, from a list of possible region codes. If the list contains more than one region, the first region for which the number is valid is returned. @param PhoneNumber $number @param $regionCodes @return String|null Region Code (or null if none are found)
[ "Helper", "method", "to", "get", "the", "region", "code", "for", "a", "given", "phone", "number", "from", "a", "list", "of", "possible", "region", "codes", ".", "If", "the", "list", "contains", "more", "than", "one", "region", "the", "first", "region", "for", "which", "the", "number", "is", "valid", "is", "returned", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/ShortNumberInfo.php#L342-L364
train
giggsey/libphonenumber-for-php
src/ShortNumberInfo.php
ShortNumberInfo.isValidShortNumberForRegion
public function isValidShortNumberForRegion(PhoneNumber $number, $regionDialingFrom) { if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) { return false; } $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom); if ($phoneMetadata === null) { return false; } $shortNumber = $this->getNationalSignificantNumber($number); $generalDesc = $phoneMetadata->getGeneralDesc(); if (!$this->matchesPossibleNumberAndNationalNumber($shortNumber, $generalDesc)) { return false; } $shortNumberDesc = $phoneMetadata->getShortCode(); return $this->matchesPossibleNumberAndNationalNumber($shortNumber, $shortNumberDesc); }
php
public function isValidShortNumberForRegion(PhoneNumber $number, $regionDialingFrom) { if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) { return false; } $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom); if ($phoneMetadata === null) { return false; } $shortNumber = $this->getNationalSignificantNumber($number); $generalDesc = $phoneMetadata->getGeneralDesc(); if (!$this->matchesPossibleNumberAndNationalNumber($shortNumber, $generalDesc)) { return false; } $shortNumberDesc = $phoneMetadata->getShortCode(); return $this->matchesPossibleNumberAndNationalNumber($shortNumber, $shortNumberDesc); }
[ "public", "function", "isValidShortNumberForRegion", "(", "PhoneNumber", "$", "number", ",", "$", "regionDialingFrom", ")", "{", "if", "(", "!", "$", "this", "->", "regionDialingFromMatchesNumber", "(", "$", "number", ",", "$", "regionDialingFrom", ")", ")", "{", "return", "false", ";", "}", "$", "phoneMetadata", "=", "$", "this", "->", "getMetadataForRegion", "(", "$", "regionDialingFrom", ")", ";", "if", "(", "$", "phoneMetadata", "===", "null", ")", "{", "return", "false", ";", "}", "$", "shortNumber", "=", "$", "this", "->", "getNationalSignificantNumber", "(", "$", "number", ")", ";", "$", "generalDesc", "=", "$", "phoneMetadata", "->", "getGeneralDesc", "(", ")", ";", "if", "(", "!", "$", "this", "->", "matchesPossibleNumberAndNationalNumber", "(", "$", "shortNumber", ",", "$", "generalDesc", ")", ")", "{", "return", "false", ";", "}", "$", "shortNumberDesc", "=", "$", "phoneMetadata", "->", "getShortCode", "(", ")", ";", "return", "$", "this", "->", "matchesPossibleNumberAndNationalNumber", "(", "$", "shortNumber", ",", "$", "shortNumberDesc", ")", ";", "}" ]
Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. @param PhoneNumber $number The Short number for which we want to test the validity @param string $regionDialingFrom the region from which the number is dialed @return boolean whether the short number matches a valid pattern
[ "Tests", "whether", "a", "short", "number", "matches", "a", "valid", "pattern", "in", "a", "region", ".", "Note", "that", "this", "doesn", "t", "verify", "the", "number", "is", "actually", "in", "use", "which", "is", "impossible", "to", "tell", "by", "just", "looking", "at", "the", "number", "itself", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/ShortNumberInfo.php#L451-L473
train
giggsey/libphonenumber-for-php
src/PhoneNumberMatcher.php
PhoneNumberMatcher.limit
protected static function limit($lower, $upper) { if (($lower < 0) || ($upper <= 0) || ($upper < $lower)) { throw new \InvalidArgumentException(); } return '{' . $lower . ',' . $upper . '}'; }
php
protected static function limit($lower, $upper) { if (($lower < 0) || ($upper <= 0) || ($upper < $lower)) { throw new \InvalidArgumentException(); } return '{' . $lower . ',' . $upper . '}'; }
[ "protected", "static", "function", "limit", "(", "$", "lower", ",", "$", "upper", ")", "{", "if", "(", "(", "$", "lower", "<", "0", ")", "||", "(", "$", "upper", "<=", "0", ")", "||", "(", "$", "upper", "<", "$", "lower", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", ")", ";", "}", "return", "'{'", ".", "$", "lower", ".", "','", ".", "$", "upper", ".", "'}'", ";", "}" ]
Helper function to generate regular expression with an upper and lower limit. @param int $lower @param int $upper @return string
[ "Helper", "function", "to", "generate", "regular", "expression", "with", "an", "upper", "and", "lower", "limit", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberMatcher.php#L200-L207
train
giggsey/libphonenumber-for-php
src/PhoneNumberMatcher.php
PhoneNumberMatcher.isLatinLetter
public static function isLatinLetter($letter) { // Combining marks are a subset of non-spacing-mark. if (preg_match('/\p{L}/u', $letter) !== 1 && preg_match('/\p{Mn}/u', $letter) !== 1) { return false; } return (preg_match('/\p{Latin}/u', $letter) === 1) || (preg_match('/\pM+/u', $letter) === 1); }
php
public static function isLatinLetter($letter) { // Combining marks are a subset of non-spacing-mark. if (preg_match('/\p{L}/u', $letter) !== 1 && preg_match('/\p{Mn}/u', $letter) !== 1) { return false; } return (preg_match('/\p{Latin}/u', $letter) === 1) || (preg_match('/\pM+/u', $letter) === 1); }
[ "public", "static", "function", "isLatinLetter", "(", "$", "letter", ")", "{", "// Combining marks are a subset of non-spacing-mark.", "if", "(", "preg_match", "(", "'/\\p{L}/u'", ",", "$", "letter", ")", "!==", "1", "&&", "preg_match", "(", "'/\\p{Mn}/u'", ",", "$", "letter", ")", "!==", "1", ")", "{", "return", "false", ";", "}", "return", "(", "preg_match", "(", "'/\\p{Latin}/u'", ",", "$", "letter", ")", "===", "1", ")", "||", "(", "preg_match", "(", "'/\\pM+/u'", ",", "$", "letter", ")", "===", "1", ")", ";", "}" ]
Helper method to determine if a character is a Latin-script letter or not. For our purposes, combining marks should also return true since we assume they have been added to a preceding Latin character. @param string $letter @return bool @internal
[ "Helper", "method", "to", "determine", "if", "a", "character", "is", "a", "Latin", "-", "script", "letter", "or", "not", ".", "For", "our", "purposes", "combining", "marks", "should", "also", "return", "true", "since", "we", "assume", "they", "have", "been", "added", "to", "a", "preceding", "Latin", "character", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberMatcher.php#L352-L361
train
giggsey/libphonenumber-for-php
src/PhoneNumberMatcher.php
PhoneNumberMatcher.getNationalNumberGroups
protected static function getNationalNumberGroups( PhoneNumberUtil $util, PhoneNumber $number, NumberFormat $formattingPattern = null ) { if ($formattingPattern === null) { // This will be in the format +CC-DG;ext=EXT where DG represents groups of digits. $rfc3966Format = $util->format($number, PhoneNumberFormat::RFC3966); // We remove the extension part from the formatted string before splitting it into different // groups. $endIndex = mb_strpos($rfc3966Format, ';'); if ($endIndex === false) { $endIndex = mb_strlen($rfc3966Format); } // The country-code will have a '-' following it. $startIndex = mb_strpos($rfc3966Format, '-') + 1; return explode('-', mb_substr($rfc3966Format, $startIndex, $endIndex - $startIndex)); } // If a format is provided, we format the NSN only, and split that according to the separator. $nationalSignificantNumber = $util->getNationalSignificantNumber($number); return explode('-', $util->formatNsnUsingPattern($nationalSignificantNumber, $formattingPattern, PhoneNumberFormat::RFC3966)); }
php
protected static function getNationalNumberGroups( PhoneNumberUtil $util, PhoneNumber $number, NumberFormat $formattingPattern = null ) { if ($formattingPattern === null) { // This will be in the format +CC-DG;ext=EXT where DG represents groups of digits. $rfc3966Format = $util->format($number, PhoneNumberFormat::RFC3966); // We remove the extension part from the formatted string before splitting it into different // groups. $endIndex = mb_strpos($rfc3966Format, ';'); if ($endIndex === false) { $endIndex = mb_strlen($rfc3966Format); } // The country-code will have a '-' following it. $startIndex = mb_strpos($rfc3966Format, '-') + 1; return explode('-', mb_substr($rfc3966Format, $startIndex, $endIndex - $startIndex)); } // If a format is provided, we format the NSN only, and split that according to the separator. $nationalSignificantNumber = $util->getNationalSignificantNumber($number); return explode('-', $util->formatNsnUsingPattern($nationalSignificantNumber, $formattingPattern, PhoneNumberFormat::RFC3966)); }
[ "protected", "static", "function", "getNationalNumberGroups", "(", "PhoneNumberUtil", "$", "util", ",", "PhoneNumber", "$", "number", ",", "NumberFormat", "$", "formattingPattern", "=", "null", ")", "{", "if", "(", "$", "formattingPattern", "===", "null", ")", "{", "// This will be in the format +CC-DG;ext=EXT where DG represents groups of digits.", "$", "rfc3966Format", "=", "$", "util", "->", "format", "(", "$", "number", ",", "PhoneNumberFormat", "::", "RFC3966", ")", ";", "// We remove the extension part from the formatted string before splitting it into different", "// groups.", "$", "endIndex", "=", "mb_strpos", "(", "$", "rfc3966Format", ",", "';'", ")", ";", "if", "(", "$", "endIndex", "===", "false", ")", "{", "$", "endIndex", "=", "mb_strlen", "(", "$", "rfc3966Format", ")", ";", "}", "// The country-code will have a '-' following it.", "$", "startIndex", "=", "mb_strpos", "(", "$", "rfc3966Format", ",", "'-'", ")", "+", "1", ";", "return", "explode", "(", "'-'", ",", "mb_substr", "(", "$", "rfc3966Format", ",", "$", "startIndex", ",", "$", "endIndex", "-", "$", "startIndex", ")", ")", ";", "}", "// If a format is provided, we format the NSN only, and split that according to the separator.", "$", "nationalSignificantNumber", "=", "$", "util", "->", "getNationalSignificantNumber", "(", "$", "number", ")", ";", "return", "explode", "(", "'-'", ",", "$", "util", "->", "formatNsnUsingPattern", "(", "$", "nationalSignificantNumber", ",", "$", "formattingPattern", ",", "PhoneNumberFormat", "::", "RFC3966", ")", ")", ";", "}" ]
Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together. @param PhoneNumberUtil $util @param PhoneNumber $number @param NumberFormat $formattingPattern @return string[]
[ "Helper", "method", "to", "get", "the", "national", "-", "number", "part", "of", "a", "number", "formatted", "without", "any", "national", "prefix", "and", "return", "it", "as", "a", "set", "of", "digit", "blocks", "that", "would", "be", "formatted", "together", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumberMatcher.php#L625-L649
train
giggsey/libphonenumber-for-php
src/PhoneNumber.php
PhoneNumber.clear
public function clear() { $this->clearCountryCode(); $this->clearNationalNumber(); $this->clearExtension(); $this->clearItalianLeadingZero(); $this->clearNumberOfLeadingZeros(); $this->clearRawInput(); $this->clearCountryCodeSource(); $this->clearPreferredDomesticCarrierCode(); return $this; }
php
public function clear() { $this->clearCountryCode(); $this->clearNationalNumber(); $this->clearExtension(); $this->clearItalianLeadingZero(); $this->clearNumberOfLeadingZeros(); $this->clearRawInput(); $this->clearCountryCodeSource(); $this->clearPreferredDomesticCarrierCode(); return $this; }
[ "public", "function", "clear", "(", ")", "{", "$", "this", "->", "clearCountryCode", "(", ")", ";", "$", "this", "->", "clearNationalNumber", "(", ")", ";", "$", "this", "->", "clearExtension", "(", ")", ";", "$", "this", "->", "clearItalianLeadingZero", "(", ")", ";", "$", "this", "->", "clearNumberOfLeadingZeros", "(", ")", ";", "$", "this", "->", "clearRawInput", "(", ")", ";", "$", "this", "->", "clearCountryCodeSource", "(", ")", ";", "$", "this", "->", "clearPreferredDomesticCarrierCode", "(", ")", ";", "return", "$", "this", ";", "}" ]
Clears this phone number. This effectively resets this phone number to the state of a new instance. @return PhoneNumber This PhoneNumber instance, for chaining method calls.
[ "Clears", "this", "phone", "number", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumber.php#L103-L114
train
giggsey/libphonenumber-for-php
src/PhoneNumber.php
PhoneNumber.mergeFrom
public function mergeFrom(PhoneNumber $other) { if ($other->hasCountryCode()) { $this->setCountryCode($other->getCountryCode()); } if ($other->hasNationalNumber()) { $this->setNationalNumber($other->getNationalNumber()); } if ($other->hasExtension()) { $this->setExtension($other->getExtension()); } if ($other->hasItalianLeadingZero()) { $this->setItalianLeadingZero($other->isItalianLeadingZero()); } if ($other->hasNumberOfLeadingZeros()) { $this->setNumberOfLeadingZeros($other->getNumberOfLeadingZeros()); } if ($other->hasRawInput()) { $this->setRawInput($other->getRawInput()); } if ($other->hasCountryCodeSource()) { $this->setCountryCodeSource($other->getCountryCodeSource()); } if ($other->hasPreferredDomesticCarrierCode()) { $this->setPreferredDomesticCarrierCode($other->getPreferredDomesticCarrierCode()); } return $this; }
php
public function mergeFrom(PhoneNumber $other) { if ($other->hasCountryCode()) { $this->setCountryCode($other->getCountryCode()); } if ($other->hasNationalNumber()) { $this->setNationalNumber($other->getNationalNumber()); } if ($other->hasExtension()) { $this->setExtension($other->getExtension()); } if ($other->hasItalianLeadingZero()) { $this->setItalianLeadingZero($other->isItalianLeadingZero()); } if ($other->hasNumberOfLeadingZeros()) { $this->setNumberOfLeadingZeros($other->getNumberOfLeadingZeros()); } if ($other->hasRawInput()) { $this->setRawInput($other->getRawInput()); } if ($other->hasCountryCodeSource()) { $this->setCountryCodeSource($other->getCountryCodeSource()); } if ($other->hasPreferredDomesticCarrierCode()) { $this->setPreferredDomesticCarrierCode($other->getPreferredDomesticCarrierCode()); } return $this; }
[ "public", "function", "mergeFrom", "(", "PhoneNumber", "$", "other", ")", "{", "if", "(", "$", "other", "->", "hasCountryCode", "(", ")", ")", "{", "$", "this", "->", "setCountryCode", "(", "$", "other", "->", "getCountryCode", "(", ")", ")", ";", "}", "if", "(", "$", "other", "->", "hasNationalNumber", "(", ")", ")", "{", "$", "this", "->", "setNationalNumber", "(", "$", "other", "->", "getNationalNumber", "(", ")", ")", ";", "}", "if", "(", "$", "other", "->", "hasExtension", "(", ")", ")", "{", "$", "this", "->", "setExtension", "(", "$", "other", "->", "getExtension", "(", ")", ")", ";", "}", "if", "(", "$", "other", "->", "hasItalianLeadingZero", "(", ")", ")", "{", "$", "this", "->", "setItalianLeadingZero", "(", "$", "other", "->", "isItalianLeadingZero", "(", ")", ")", ";", "}", "if", "(", "$", "other", "->", "hasNumberOfLeadingZeros", "(", ")", ")", "{", "$", "this", "->", "setNumberOfLeadingZeros", "(", "$", "other", "->", "getNumberOfLeadingZeros", "(", ")", ")", ";", "}", "if", "(", "$", "other", "->", "hasRawInput", "(", ")", ")", "{", "$", "this", "->", "setRawInput", "(", "$", "other", "->", "getRawInput", "(", ")", ")", ";", "}", "if", "(", "$", "other", "->", "hasCountryCodeSource", "(", ")", ")", "{", "$", "this", "->", "setCountryCodeSource", "(", "$", "other", "->", "getCountryCodeSource", "(", ")", ")", ";", "}", "if", "(", "$", "other", "->", "hasPreferredDomesticCarrierCode", "(", ")", ")", "{", "$", "this", "->", "setPreferredDomesticCarrierCode", "(", "$", "other", "->", "getPreferredDomesticCarrierCode", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Merges the information from another phone number into this phone number. @param PhoneNumber $other The phone number to copy. @return PhoneNumber This PhoneNumber instance, for chaining method calls.
[ "Merges", "the", "information", "from", "another", "phone", "number", "into", "this", "phone", "number", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumber.php#L212-L239
train
giggsey/libphonenumber-for-php
src/PhoneNumber.php
PhoneNumber.setNumberOfLeadingZeros
public function setNumberOfLeadingZeros($value) { $this->hasNumberOfLeadingZeros = true; $this->numberOfLeadingZeros = (int) $value; return $this; }
php
public function setNumberOfLeadingZeros($value) { $this->hasNumberOfLeadingZeros = true; $this->numberOfLeadingZeros = (int) $value; return $this; }
[ "public", "function", "setNumberOfLeadingZeros", "(", "$", "value", ")", "{", "$", "this", "->", "hasNumberOfLeadingZeros", "=", "true", ";", "$", "this", "->", "numberOfLeadingZeros", "=", "(", "int", ")", "$", "value", ";", "return", "$", "this", ";", "}" ]
Sets the number of leading zeros of this phone number. @param int $value The number of leading zeros. @return PhoneNumber This PhoneNumber instance, for chaining method calls.
[ "Sets", "the", "number", "of", "leading", "zeros", "of", "this", "phone", "number", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumber.php#L400-L405
train
giggsey/libphonenumber-for-php
src/PhoneNumber.php
PhoneNumber.equals
public function equals(PhoneNumber $other) { $sameType = get_class($other) == get_class($this); $sameCountry = $this->hasCountryCode() == $other->hasCountryCode() && (!$this->hasCountryCode() || $this->getCountryCode() == $other->getCountryCode()); $sameNational = $this->hasNationalNumber() == $other->hasNationalNumber() && (!$this->hasNationalNumber() || $this->getNationalNumber() == $other->getNationalNumber()); $sameExt = $this->hasExtension() == $other->hasExtension() && (!$this->hasExtension() || $this->hasExtension() == $other->hasExtension()); $sameLead = $this->hasItalianLeadingZero() == $other->hasItalianLeadingZero() && (!$this->hasItalianLeadingZero() || $this->isItalianLeadingZero() == $other->isItalianLeadingZero()); $sameZeros = $this->getNumberOfLeadingZeros() == $other->getNumberOfLeadingZeros(); $sameRaw = $this->hasRawInput() == $other->hasRawInput() && (!$this->hasRawInput() || $this->getRawInput() == $other->getRawInput()); $sameCountrySource = $this->hasCountryCodeSource() == $other->hasCountryCodeSource() && (!$this->hasCountryCodeSource() || $this->getCountryCodeSource() == $other->getCountryCodeSource()); $samePrefCar = $this->hasPreferredDomesticCarrierCode() == $other->hasPreferredDomesticCarrierCode() && (!$this->hasPreferredDomesticCarrierCode() || $this->getPreferredDomesticCarrierCode( ) == $other->getPreferredDomesticCarrierCode()); return $sameType && $sameCountry && $sameNational && $sameExt && $sameLead && $sameZeros && $sameRaw && $sameCountrySource && $samePrefCar; }
php
public function equals(PhoneNumber $other) { $sameType = get_class($other) == get_class($this); $sameCountry = $this->hasCountryCode() == $other->hasCountryCode() && (!$this->hasCountryCode() || $this->getCountryCode() == $other->getCountryCode()); $sameNational = $this->hasNationalNumber() == $other->hasNationalNumber() && (!$this->hasNationalNumber() || $this->getNationalNumber() == $other->getNationalNumber()); $sameExt = $this->hasExtension() == $other->hasExtension() && (!$this->hasExtension() || $this->hasExtension() == $other->hasExtension()); $sameLead = $this->hasItalianLeadingZero() == $other->hasItalianLeadingZero() && (!$this->hasItalianLeadingZero() || $this->isItalianLeadingZero() == $other->isItalianLeadingZero()); $sameZeros = $this->getNumberOfLeadingZeros() == $other->getNumberOfLeadingZeros(); $sameRaw = $this->hasRawInput() == $other->hasRawInput() && (!$this->hasRawInput() || $this->getRawInput() == $other->getRawInput()); $sameCountrySource = $this->hasCountryCodeSource() == $other->hasCountryCodeSource() && (!$this->hasCountryCodeSource() || $this->getCountryCodeSource() == $other->getCountryCodeSource()); $samePrefCar = $this->hasPreferredDomesticCarrierCode() == $other->hasPreferredDomesticCarrierCode() && (!$this->hasPreferredDomesticCarrierCode() || $this->getPreferredDomesticCarrierCode( ) == $other->getPreferredDomesticCarrierCode()); return $sameType && $sameCountry && $sameNational && $sameExt && $sameLead && $sameZeros && $sameRaw && $sameCountrySource && $samePrefCar; }
[ "public", "function", "equals", "(", "PhoneNumber", "$", "other", ")", "{", "$", "sameType", "=", "get_class", "(", "$", "other", ")", "==", "get_class", "(", "$", "this", ")", ";", "$", "sameCountry", "=", "$", "this", "->", "hasCountryCode", "(", ")", "==", "$", "other", "->", "hasCountryCode", "(", ")", "&&", "(", "!", "$", "this", "->", "hasCountryCode", "(", ")", "||", "$", "this", "->", "getCountryCode", "(", ")", "==", "$", "other", "->", "getCountryCode", "(", ")", ")", ";", "$", "sameNational", "=", "$", "this", "->", "hasNationalNumber", "(", ")", "==", "$", "other", "->", "hasNationalNumber", "(", ")", "&&", "(", "!", "$", "this", "->", "hasNationalNumber", "(", ")", "||", "$", "this", "->", "getNationalNumber", "(", ")", "==", "$", "other", "->", "getNationalNumber", "(", ")", ")", ";", "$", "sameExt", "=", "$", "this", "->", "hasExtension", "(", ")", "==", "$", "other", "->", "hasExtension", "(", ")", "&&", "(", "!", "$", "this", "->", "hasExtension", "(", ")", "||", "$", "this", "->", "hasExtension", "(", ")", "==", "$", "other", "->", "hasExtension", "(", ")", ")", ";", "$", "sameLead", "=", "$", "this", "->", "hasItalianLeadingZero", "(", ")", "==", "$", "other", "->", "hasItalianLeadingZero", "(", ")", "&&", "(", "!", "$", "this", "->", "hasItalianLeadingZero", "(", ")", "||", "$", "this", "->", "isItalianLeadingZero", "(", ")", "==", "$", "other", "->", "isItalianLeadingZero", "(", ")", ")", ";", "$", "sameZeros", "=", "$", "this", "->", "getNumberOfLeadingZeros", "(", ")", "==", "$", "other", "->", "getNumberOfLeadingZeros", "(", ")", ";", "$", "sameRaw", "=", "$", "this", "->", "hasRawInput", "(", ")", "==", "$", "other", "->", "hasRawInput", "(", ")", "&&", "(", "!", "$", "this", "->", "hasRawInput", "(", ")", "||", "$", "this", "->", "getRawInput", "(", ")", "==", "$", "other", "->", "getRawInput", "(", ")", ")", ";", "$", "sameCountrySource", "=", "$", "this", "->", "hasCountryCodeSource", "(", ")", "==", "$", "other", "->", "hasCountryCodeSource", "(", ")", "&&", "(", "!", "$", "this", "->", "hasCountryCodeSource", "(", ")", "||", "$", "this", "->", "getCountryCodeSource", "(", ")", "==", "$", "other", "->", "getCountryCodeSource", "(", ")", ")", ";", "$", "samePrefCar", "=", "$", "this", "->", "hasPreferredDomesticCarrierCode", "(", ")", "==", "$", "other", "->", "hasPreferredDomesticCarrierCode", "(", ")", "&&", "(", "!", "$", "this", "->", "hasPreferredDomesticCarrierCode", "(", ")", "||", "$", "this", "->", "getPreferredDomesticCarrierCode", "(", ")", "==", "$", "other", "->", "getPreferredDomesticCarrierCode", "(", ")", ")", ";", "return", "$", "sameType", "&&", "$", "sameCountry", "&&", "$", "sameNational", "&&", "$", "sameExt", "&&", "$", "sameLead", "&&", "$", "sameZeros", "&&", "$", "sameRaw", "&&", "$", "sameCountrySource", "&&", "$", "samePrefCar", ";", "}" ]
Returns whether this phone number is equal to another. @param PhoneNumber $other The phone number to compare. @return bool True if the phone numbers are equal, false otherwise.
[ "Returns", "whether", "this", "phone", "number", "is", "equal", "to", "another", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/PhoneNumber.php#L513-L533
train
giggsey/libphonenumber-for-php
build/GenerateTimeZonesMapData.php
GenerateTimeZonesMapData.parseTextFile
private function parseTextFile() { $data = file($this->inputTextFile); $timeZoneMap = array(); foreach ($data as $line) { // Remove \n $line = str_replace(array("\n", "\r"), '', $line); $line = trim($line); if (strlen($line) == 0 || substr($line, 0, 1) == '#') { continue; } if (strpos($line, '|')) { // Valid line $parts = explode('|', $line); $prefix = $parts[0]; $timezone = $parts[1]; $timeZoneMap[$prefix] = $timezone; } } return $timeZoneMap; }
php
private function parseTextFile() { $data = file($this->inputTextFile); $timeZoneMap = array(); foreach ($data as $line) { // Remove \n $line = str_replace(array("\n", "\r"), '', $line); $line = trim($line); if (strlen($line) == 0 || substr($line, 0, 1) == '#') { continue; } if (strpos($line, '|')) { // Valid line $parts = explode('|', $line); $prefix = $parts[0]; $timezone = $parts[1]; $timeZoneMap[$prefix] = $timezone; } } return $timeZoneMap; }
[ "private", "function", "parseTextFile", "(", ")", "{", "$", "data", "=", "file", "(", "$", "this", "->", "inputTextFile", ")", ";", "$", "timeZoneMap", "=", "array", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "line", ")", "{", "// Remove \\n", "$", "line", "=", "str_replace", "(", "array", "(", "\"\\n\"", ",", "\"\\r\"", ")", ",", "''", ",", "$", "line", ")", ";", "$", "line", "=", "trim", "(", "$", "line", ")", ";", "if", "(", "strlen", "(", "$", "line", ")", "==", "0", "||", "substr", "(", "$", "line", ",", "0", ",", "1", ")", "==", "'#'", ")", "{", "continue", ";", "}", "if", "(", "strpos", "(", "$", "line", ",", "'|'", ")", ")", "{", "// Valid line", "$", "parts", "=", "explode", "(", "'|'", ",", "$", "line", ")", ";", "$", "prefix", "=", "$", "parts", "[", "0", "]", ";", "$", "timezone", "=", "$", "parts", "[", "1", "]", ";", "$", "timeZoneMap", "[", "$", "prefix", "]", "=", "$", "timezone", ";", "}", "}", "return", "$", "timeZoneMap", ";", "}" ]
Reads phone prefix data from the provided input stream and returns a SortedMap with the prefix to time zones mappings.
[ "Reads", "phone", "prefix", "data", "from", "the", "provided", "input", "stream", "and", "returns", "a", "SortedMap", "with", "the", "prefix", "to", "time", "zones", "mappings", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/build/GenerateTimeZonesMapData.php#L47-L74
train
giggsey/libphonenumber-for-php
src/geocoding/PhoneNumberOfflineGeocoder.php
PhoneNumberOfflineGeocoder.getDescriptionForNumber
public function getDescriptionForNumber(PhoneNumber $number, $locale, $userRegion = null) { $numberType = $this->phoneUtil->getNumberType($number); if ($numberType === PhoneNumberType::UNKNOWN) { return ''; } if (!$this->phoneUtil->isNumberGeographical($numberType, $number->getCountryCode())) { return $this->getCountryNameForNumber($number, $locale); } return $this->getDescriptionForValidNumber($number, $locale, $userRegion); }
php
public function getDescriptionForNumber(PhoneNumber $number, $locale, $userRegion = null) { $numberType = $this->phoneUtil->getNumberType($number); if ($numberType === PhoneNumberType::UNKNOWN) { return ''; } if (!$this->phoneUtil->isNumberGeographical($numberType, $number->getCountryCode())) { return $this->getCountryNameForNumber($number, $locale); } return $this->getDescriptionForValidNumber($number, $locale, $userRegion); }
[ "public", "function", "getDescriptionForNumber", "(", "PhoneNumber", "$", "number", ",", "$", "locale", ",", "$", "userRegion", "=", "null", ")", "{", "$", "numberType", "=", "$", "this", "->", "phoneUtil", "->", "getNumberType", "(", "$", "number", ")", ";", "if", "(", "$", "numberType", "===", "PhoneNumberType", "::", "UNKNOWN", ")", "{", "return", "''", ";", "}", "if", "(", "!", "$", "this", "->", "phoneUtil", "->", "isNumberGeographical", "(", "$", "numberType", ",", "$", "number", "->", "getCountryCode", "(", ")", ")", ")", "{", "return", "$", "this", "->", "getCountryNameForNumber", "(", "$", "number", ",", "$", "locale", ")", ";", "}", "return", "$", "this", "->", "getDescriptionForValidNumber", "(", "$", "number", ",", "$", "locale", ",", "$", "userRegion", ")", ";", "}" ]
As per getDescriptionForValidNumber, but explicitly checks the validity of the number passed in. @see getDescriptionForValidNumber @param PhoneNumber $number a valid phone number for which we want to get a text description @param string $locale the language code for which the description should be written @param string $userRegion the region code for a given user. This region will be omitted from the description if the phone number comes from this region. It is a two-letter uppercase CLDR region code. @return string a text description for the given language code for the given phone number, or empty string if the number passed in is invalid
[ "As", "per", "getDescriptionForValidNumber", "but", "explicitly", "checks", "the", "validity", "of", "the", "number", "passed", "in", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/geocoding/PhoneNumberOfflineGeocoder.php#L76-L89
train
giggsey/libphonenumber-for-php
src/geocoding/PhoneNumberOfflineGeocoder.php
PhoneNumberOfflineGeocoder.getCountryNameForNumber
protected function getCountryNameForNumber(PhoneNumber $number, $locale) { $regionCodes = $this->phoneUtil->getRegionCodesForCountryCode($number->getCountryCode()); if (count($regionCodes) === 1) { return $this->getRegionDisplayName($regionCodes[0], $locale); } $regionWhereNumberIsValid = 'ZZ'; foreach ($regionCodes as $regionCode) { if ($this->phoneUtil->isValidNumberForRegion($number, $regionCode)) { // If the number has already been found valid for one region, then we don't know which // region it belongs to so we return nothing. if ($regionWhereNumberIsValid !== 'ZZ') { return ''; } $regionWhereNumberIsValid = $regionCode; } } return $this->getRegionDisplayName($regionWhereNumberIsValid, $locale); }
php
protected function getCountryNameForNumber(PhoneNumber $number, $locale) { $regionCodes = $this->phoneUtil->getRegionCodesForCountryCode($number->getCountryCode()); if (count($regionCodes) === 1) { return $this->getRegionDisplayName($regionCodes[0], $locale); } $regionWhereNumberIsValid = 'ZZ'; foreach ($regionCodes as $regionCode) { if ($this->phoneUtil->isValidNumberForRegion($number, $regionCode)) { // If the number has already been found valid for one region, then we don't know which // region it belongs to so we return nothing. if ($regionWhereNumberIsValid !== 'ZZ') { return ''; } $regionWhereNumberIsValid = $regionCode; } } return $this->getRegionDisplayName($regionWhereNumberIsValid, $locale); }
[ "protected", "function", "getCountryNameForNumber", "(", "PhoneNumber", "$", "number", ",", "$", "locale", ")", "{", "$", "regionCodes", "=", "$", "this", "->", "phoneUtil", "->", "getRegionCodesForCountryCode", "(", "$", "number", "->", "getCountryCode", "(", ")", ")", ";", "if", "(", "count", "(", "$", "regionCodes", ")", "===", "1", ")", "{", "return", "$", "this", "->", "getRegionDisplayName", "(", "$", "regionCodes", "[", "0", "]", ",", "$", "locale", ")", ";", "}", "$", "regionWhereNumberIsValid", "=", "'ZZ'", ";", "foreach", "(", "$", "regionCodes", "as", "$", "regionCode", ")", "{", "if", "(", "$", "this", "->", "phoneUtil", "->", "isValidNumberForRegion", "(", "$", "number", ",", "$", "regionCode", ")", ")", "{", "// If the number has already been found valid for one region, then we don't know which", "// region it belongs to so we return nothing.", "if", "(", "$", "regionWhereNumberIsValid", "!==", "'ZZ'", ")", "{", "return", "''", ";", "}", "$", "regionWhereNumberIsValid", "=", "$", "regionCode", ";", "}", "}", "return", "$", "this", "->", "getRegionDisplayName", "(", "$", "regionWhereNumberIsValid", ",", "$", "locale", ")", ";", "}" ]
Returns the customary display name in the given language for the given territory the phone number is from. If it could be from many territories, nothing is returned. @param PhoneNumber $number @param string $locale @return string
[ "Returns", "the", "customary", "display", "name", "in", "the", "given", "language", "for", "the", "given", "territory", "the", "phone", "number", "is", "from", ".", "If", "it", "could", "be", "from", "many", "territories", "nothing", "is", "returned", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/geocoding/PhoneNumberOfflineGeocoder.php#L99-L120
train
giggsey/libphonenumber-for-php
src/geocoding/PhoneNumberOfflineGeocoder.php
PhoneNumberOfflineGeocoder.getRegionDisplayName
protected function getRegionDisplayName($regionCode, $locale) { if ($regionCode === null || $regionCode == 'ZZ' || $regionCode === PhoneNumberUtil::REGION_CODE_FOR_NON_GEO_ENTITY) { return ''; } return Locale::getDisplayRegion( '-' . $regionCode, $locale ); }
php
protected function getRegionDisplayName($regionCode, $locale) { if ($regionCode === null || $regionCode == 'ZZ' || $regionCode === PhoneNumberUtil::REGION_CODE_FOR_NON_GEO_ENTITY) { return ''; } return Locale::getDisplayRegion( '-' . $regionCode, $locale ); }
[ "protected", "function", "getRegionDisplayName", "(", "$", "regionCode", ",", "$", "locale", ")", "{", "if", "(", "$", "regionCode", "===", "null", "||", "$", "regionCode", "==", "'ZZ'", "||", "$", "regionCode", "===", "PhoneNumberUtil", "::", "REGION_CODE_FOR_NON_GEO_ENTITY", ")", "{", "return", "''", ";", "}", "return", "Locale", "::", "getDisplayRegion", "(", "'-'", ".", "$", "regionCode", ",", "$", "locale", ")", ";", "}" ]
Returns the customary display name in the given language for the given region. @param $regionCode @param $locale @return string
[ "Returns", "the", "customary", "display", "name", "in", "the", "given", "language", "for", "the", "given", "region", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/geocoding/PhoneNumberOfflineGeocoder.php#L129-L139
train
giggsey/libphonenumber-for-php
src/geocoding/PhoneNumberOfflineGeocoder.php
PhoneNumberOfflineGeocoder.getDescriptionForValidNumber
public function getDescriptionForValidNumber(PhoneNumber $number, $locale, $userRegion = null) { // If the user region matches the number's region, then we just show the lower-level // description, if one exists - if no description exists, we will show the region(country) name // for the number. $regionCode = $this->phoneUtil->getRegionCodeForNumber($number); if ($userRegion == null || $userRegion == $regionCode) { $languageStr = Locale::getPrimaryLanguage($locale); $scriptStr = ''; $regionStr = Locale::getRegion($locale); $mobileToken = PhoneNumberUtil::getCountryMobileToken($number->getCountryCode()); $nationalNumber = $this->phoneUtil->getNationalSignificantNumber($number); if ($mobileToken !== '' && (!strncmp($nationalNumber, $mobileToken, strlen($mobileToken)))) { // In some countries, eg. Argentina, mobile numbers have a mobile token before the national // destination code, this should be removed before geocoding. $nationalNumber = substr($nationalNumber, strlen($mobileToken)); $region = $this->phoneUtil->getRegionCodeForCountryCode($number->getCountryCode()); try { $copiedNumber = $this->phoneUtil->parse($nationalNumber, $region); } catch (NumberParseException $e) { // If this happens, just reuse what we had. $copiedNumber = $number; } $areaDescription = $this->prefixFileReader->getDescriptionForNumber($copiedNumber, $languageStr, $scriptStr, $regionStr); } else { $areaDescription = $this->prefixFileReader->getDescriptionForNumber($number, $languageStr, $scriptStr, $regionStr); } return (strlen($areaDescription) > 0) ? $areaDescription : $this->getCountryNameForNumber($number, $locale); } // Otherwise, we just show the region(country) name for now. return $this->getRegionDisplayName($regionCode, $locale); // TODO: Concatenate the lower-level and country-name information in an appropriate // way for each language. }
php
public function getDescriptionForValidNumber(PhoneNumber $number, $locale, $userRegion = null) { // If the user region matches the number's region, then we just show the lower-level // description, if one exists - if no description exists, we will show the region(country) name // for the number. $regionCode = $this->phoneUtil->getRegionCodeForNumber($number); if ($userRegion == null || $userRegion == $regionCode) { $languageStr = Locale::getPrimaryLanguage($locale); $scriptStr = ''; $regionStr = Locale::getRegion($locale); $mobileToken = PhoneNumberUtil::getCountryMobileToken($number->getCountryCode()); $nationalNumber = $this->phoneUtil->getNationalSignificantNumber($number); if ($mobileToken !== '' && (!strncmp($nationalNumber, $mobileToken, strlen($mobileToken)))) { // In some countries, eg. Argentina, mobile numbers have a mobile token before the national // destination code, this should be removed before geocoding. $nationalNumber = substr($nationalNumber, strlen($mobileToken)); $region = $this->phoneUtil->getRegionCodeForCountryCode($number->getCountryCode()); try { $copiedNumber = $this->phoneUtil->parse($nationalNumber, $region); } catch (NumberParseException $e) { // If this happens, just reuse what we had. $copiedNumber = $number; } $areaDescription = $this->prefixFileReader->getDescriptionForNumber($copiedNumber, $languageStr, $scriptStr, $regionStr); } else { $areaDescription = $this->prefixFileReader->getDescriptionForNumber($number, $languageStr, $scriptStr, $regionStr); } return (strlen($areaDescription) > 0) ? $areaDescription : $this->getCountryNameForNumber($number, $locale); } // Otherwise, we just show the region(country) name for now. return $this->getRegionDisplayName($regionCode, $locale); // TODO: Concatenate the lower-level and country-name information in an appropriate // way for each language. }
[ "public", "function", "getDescriptionForValidNumber", "(", "PhoneNumber", "$", "number", ",", "$", "locale", ",", "$", "userRegion", "=", "null", ")", "{", "// If the user region matches the number's region, then we just show the lower-level", "// description, if one exists - if no description exists, we will show the region(country) name", "// for the number.", "$", "regionCode", "=", "$", "this", "->", "phoneUtil", "->", "getRegionCodeForNumber", "(", "$", "number", ")", ";", "if", "(", "$", "userRegion", "==", "null", "||", "$", "userRegion", "==", "$", "regionCode", ")", "{", "$", "languageStr", "=", "Locale", "::", "getPrimaryLanguage", "(", "$", "locale", ")", ";", "$", "scriptStr", "=", "''", ";", "$", "regionStr", "=", "Locale", "::", "getRegion", "(", "$", "locale", ")", ";", "$", "mobileToken", "=", "PhoneNumberUtil", "::", "getCountryMobileToken", "(", "$", "number", "->", "getCountryCode", "(", ")", ")", ";", "$", "nationalNumber", "=", "$", "this", "->", "phoneUtil", "->", "getNationalSignificantNumber", "(", "$", "number", ")", ";", "if", "(", "$", "mobileToken", "!==", "''", "&&", "(", "!", "strncmp", "(", "$", "nationalNumber", ",", "$", "mobileToken", ",", "strlen", "(", "$", "mobileToken", ")", ")", ")", ")", "{", "// In some countries, eg. Argentina, mobile numbers have a mobile token before the national", "// destination code, this should be removed before geocoding.", "$", "nationalNumber", "=", "substr", "(", "$", "nationalNumber", ",", "strlen", "(", "$", "mobileToken", ")", ")", ";", "$", "region", "=", "$", "this", "->", "phoneUtil", "->", "getRegionCodeForCountryCode", "(", "$", "number", "->", "getCountryCode", "(", ")", ")", ";", "try", "{", "$", "copiedNumber", "=", "$", "this", "->", "phoneUtil", "->", "parse", "(", "$", "nationalNumber", ",", "$", "region", ")", ";", "}", "catch", "(", "NumberParseException", "$", "e", ")", "{", "// If this happens, just reuse what we had.", "$", "copiedNumber", "=", "$", "number", ";", "}", "$", "areaDescription", "=", "$", "this", "->", "prefixFileReader", "->", "getDescriptionForNumber", "(", "$", "copiedNumber", ",", "$", "languageStr", ",", "$", "scriptStr", ",", "$", "regionStr", ")", ";", "}", "else", "{", "$", "areaDescription", "=", "$", "this", "->", "prefixFileReader", "->", "getDescriptionForNumber", "(", "$", "number", ",", "$", "languageStr", ",", "$", "scriptStr", ",", "$", "regionStr", ")", ";", "}", "return", "(", "strlen", "(", "$", "areaDescription", ")", ">", "0", ")", "?", "$", "areaDescription", ":", "$", "this", "->", "getCountryNameForNumber", "(", "$", "number", ",", "$", "locale", ")", ";", "}", "// Otherwise, we just show the region(country) name for now.", "return", "$", "this", "->", "getRegionDisplayName", "(", "$", "regionCode", ",", "$", "locale", ")", ";", "// TODO: Concatenate the lower-level and country-name information in an appropriate", "// way for each language.", "}" ]
Returns a text description for the given phone number, in the language provided. The description might consist of the name of the country where the phone number is from, or the name of the geographical area the phone number is from if more detailed information is available. <p>This method assumes the validity of the number passed in has already been checked, and that the number is suitable for geocoding. We consider fixed-line and mobile numbers possible candidates for geocoding. <p>If $userRegion is set, we also consider the region of the user. If the phone number is from the same region as the user, only a lower-level description will be returned, if one exists. Otherwise, the phone number's region will be returned, with optionally some more detailed information. <p>For example, for a user from the region "US" (United States), we would show "Mountain View, CA" for a particular number, omitting the United States from the description. For a user from the United Kingdom (region "GB"), for the same number we may show "Mountain View, CA, United States" or even just "United States". @param PhoneNumber $number a valid phone number for which we want to get a text description @param string $locale the language code for which the description should be written @param string $userRegion the region code for a given user. This region will be omitted from the description if the phone number comes from this region. It is a two-letter upper-case CLDR region code. @return string a text description for the given language code for the given phone number, or an empty string if the number could come from multiple countries, or the country code is in fact invalid
[ "Returns", "a", "text", "description", "for", "the", "given", "phone", "number", "in", "the", "language", "provided", ".", "The", "description", "might", "consist", "of", "the", "name", "of", "the", "country", "where", "the", "phone", "number", "is", "from", "or", "the", "name", "of", "the", "geographical", "area", "the", "phone", "number", "is", "from", "if", "more", "detailed", "information", "is", "available", "." ]
98f5983a33d704eafea7cc6e1cc2581883a51ddc
https://github.com/giggsey/libphonenumber-for-php/blob/98f5983a33d704eafea7cc6e1cc2581883a51ddc/src/geocoding/PhoneNumberOfflineGeocoder.php#L170-L205
train
yiisoft/yii-core
src/helpers/BaseIpHelper.php
BaseIpHelper.expandIPv6
public static function expandIPv6($ip) { $addr = inet_pton($ip); if ($addr === false) { return false; } $hex = unpack('H*hex', $addr); return substr(preg_replace('/([a-f0-9]{4})/i', '$1:', $hex['hex']), 0, -1); }
php
public static function expandIPv6($ip) { $addr = inet_pton($ip); if ($addr === false) { return false; } $hex = unpack('H*hex', $addr); return substr(preg_replace('/([a-f0-9]{4})/i', '$1:', $hex['hex']), 0, -1); }
[ "public", "static", "function", "expandIPv6", "(", "$", "ip", ")", "{", "$", "addr", "=", "inet_pton", "(", "$", "ip", ")", ";", "if", "(", "$", "addr", "===", "false", ")", "{", "return", "false", ";", "}", "$", "hex", "=", "unpack", "(", "'H*hex'", ",", "$", "addr", ")", ";", "return", "substr", "(", "preg_replace", "(", "'/([a-f0-9]{4})/i'", ",", "'$1:'", ",", "$", "hex", "[", "'hex'", "]", ")", ",", "0", ",", "-", "1", ")", ";", "}" ]
Expands an IPv6 address to it's full notation. For example `2001:db8::1` will be expanded to `2001:0db8:0000:0000:0000:0000:0000:0001` @param string $ip the original valid IPv6 address @return string|false the expanded IPv6 address; or boolean false, if IP address parsing failed
[ "Expands", "an", "IPv6", "address", "to", "it", "s", "full", "notation", "." ]
50c9eb923394c822d86bfc954cf026a7396bc95a
https://github.com/yiisoft/yii-core/blob/50c9eb923394c822d86bfc954cf026a7396bc95a/src/helpers/BaseIpHelper.php#L94-L103
train
yiisoft/yii-core
src/mail/Template.php
Template.compose
public function compose(MessageInterface $message, $params = []) { $this->message = $message; if (is_array($this->viewName)) { if (isset($this->viewName['html'])) { $html = $this->render($this->viewName['html'], $params, $this->htmlLayout); } if (isset($this->viewName['text'])) { $text = $this->render($this->viewName['text'], $params, $this->textLayout); } } else { $html = $this->render($this->viewName, $params, $this->htmlLayout); } if (isset($html)) { $this->message->setHtmlBody($html); } if (isset($text)) { $this->message->setTextBody($text); } elseif (isset($html)) { if (preg_match('~<body[^>]*>(.*?)</body>~is', $html, $match)) { $html = $match[1]; } // remove style and script $html = preg_replace('~<((style|script))[^>]*>(.*?)</\1>~is', '', $html); // strip all HTML tags and decode HTML entities $text = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5); // improve whitespace $text = preg_replace("~^[ \t]+~m", '', trim($text)); $text = preg_replace('~\R\R+~mu', "\n\n", $text); $this->message->setTextBody($text); } }
php
public function compose(MessageInterface $message, $params = []) { $this->message = $message; if (is_array($this->viewName)) { if (isset($this->viewName['html'])) { $html = $this->render($this->viewName['html'], $params, $this->htmlLayout); } if (isset($this->viewName['text'])) { $text = $this->render($this->viewName['text'], $params, $this->textLayout); } } else { $html = $this->render($this->viewName, $params, $this->htmlLayout); } if (isset($html)) { $this->message->setHtmlBody($html); } if (isset($text)) { $this->message->setTextBody($text); } elseif (isset($html)) { if (preg_match('~<body[^>]*>(.*?)</body>~is', $html, $match)) { $html = $match[1]; } // remove style and script $html = preg_replace('~<((style|script))[^>]*>(.*?)</\1>~is', '', $html); // strip all HTML tags and decode HTML entities $text = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5); // improve whitespace $text = preg_replace("~^[ \t]+~m", '', trim($text)); $text = preg_replace('~\R\R+~mu', "\n\n", $text); $this->message->setTextBody($text); } }
[ "public", "function", "compose", "(", "MessageInterface", "$", "message", ",", "$", "params", "=", "[", "]", ")", "{", "$", "this", "->", "message", "=", "$", "message", ";", "if", "(", "is_array", "(", "$", "this", "->", "viewName", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "viewName", "[", "'html'", "]", ")", ")", "{", "$", "html", "=", "$", "this", "->", "render", "(", "$", "this", "->", "viewName", "[", "'html'", "]", ",", "$", "params", ",", "$", "this", "->", "htmlLayout", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "viewName", "[", "'text'", "]", ")", ")", "{", "$", "text", "=", "$", "this", "->", "render", "(", "$", "this", "->", "viewName", "[", "'text'", "]", ",", "$", "params", ",", "$", "this", "->", "textLayout", ")", ";", "}", "}", "else", "{", "$", "html", "=", "$", "this", "->", "render", "(", "$", "this", "->", "viewName", ",", "$", "params", ",", "$", "this", "->", "htmlLayout", ")", ";", "}", "if", "(", "isset", "(", "$", "html", ")", ")", "{", "$", "this", "->", "message", "->", "setHtmlBody", "(", "$", "html", ")", ";", "}", "if", "(", "isset", "(", "$", "text", ")", ")", "{", "$", "this", "->", "message", "->", "setTextBody", "(", "$", "text", ")", ";", "}", "elseif", "(", "isset", "(", "$", "html", ")", ")", "{", "if", "(", "preg_match", "(", "'~<body[^>]*>(.*?)</body>~is'", ",", "$", "html", ",", "$", "match", ")", ")", "{", "$", "html", "=", "$", "match", "[", "1", "]", ";", "}", "// remove style and script", "$", "html", "=", "preg_replace", "(", "'~<((style|script))[^>]*>(.*?)</\\1>~is'", ",", "''", ",", "$", "html", ")", ";", "// strip all HTML tags and decode HTML entities", "$", "text", "=", "html_entity_decode", "(", "strip_tags", "(", "$", "html", ")", ",", "ENT_QUOTES", "|", "ENT_HTML5", ")", ";", "// improve whitespace", "$", "text", "=", "preg_replace", "(", "\"~^[ \\t]+~m\"", ",", "''", ",", "trim", "(", "$", "text", ")", ")", ";", "$", "text", "=", "preg_replace", "(", "'~\\R\\R+~mu'", ",", "\"\\n\\n\"", ",", "$", "text", ")", ";", "$", "this", "->", "message", "->", "setTextBody", "(", "$", "text", ")", ";", "}", "}" ]
Composes the given mail message according to this template. @param MessageInterface $message the message to be composed. @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
[ "Composes", "the", "given", "mail", "message", "according", "to", "this", "template", "." ]
50c9eb923394c822d86bfc954cf026a7396bc95a
https://github.com/yiisoft/yii-core/blob/50c9eb923394c822d86bfc954cf026a7396bc95a/src/mail/Template.php#L79-L112
train