repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
LapaLabs/YoutubeHelper
|
Resource/YoutubeResource.php
|
YoutubeResource.buildEmbedHtml
|
public function buildEmbedHtml(array $attributes = [], array $parameters = [])
{
// <iframe width="560" height="315" src="https://www.youtube.com/embed/5qanlirrRWs" frameborder="0" allowfullscreen></iframe>
$attributes = array_merge($this->attributes, $attributes, [
'src' => $this->buildEmbedUrl($parameters), // required attribute
]);
$attributeStrings = [''];
foreach ($attributes as $name => $value) {
$attributeString = (string)$name;
if (null !== $value) {
$attributeString .= '="'.htmlspecialchars($value).'"';
}
$attributeStrings[] = $attributeString;
}
return '<iframe'.implode(' ', $attributeStrings).'></iframe>';
}
|
php
|
public function buildEmbedHtml(array $attributes = [], array $parameters = [])
{
// <iframe width="560" height="315" src="https://www.youtube.com/embed/5qanlirrRWs" frameborder="0" allowfullscreen></iframe>
$attributes = array_merge($this->attributes, $attributes, [
'src' => $this->buildEmbedUrl($parameters), // required attribute
]);
$attributeStrings = [''];
foreach ($attributes as $name => $value) {
$attributeString = (string)$name;
if (null !== $value) {
$attributeString .= '="'.htmlspecialchars($value).'"';
}
$attributeStrings[] = $attributeString;
}
return '<iframe'.implode(' ', $attributeStrings).'></iframe>';
}
|
Build the valid HTML code to embed this resource
@param array $attributes
@param array $parameters
@return string
|
https://github.com/LapaLabs/YoutubeHelper/blob/b94fd4700881494d24f14fb39ed8093215d0b25b/Resource/YoutubeResource.php#L230-L247
|
cityware/city-format
|
src/Text.php
|
Text.seemsUtf8
|
public static function seemsUtf8($Str) { # by bmorel at ssi dot fr
$length = strlen($Str);
for ($i = 0; $i < $length; $i++) {
if (ord($Str[$i]) < 0x80)
continue;# 0bbbbbbb
elseif ((ord($Str[$i]) & 0xE0) == 0xC0)
$n = 1;# 110bbbbb
elseif ((ord($Str[$i]) & 0xF0) == 0xE0)
$n = 2;# 1110bbbb
elseif ((ord($Str[$i]) & 0xF8) == 0xF0)
$n = 3;# 11110bbb
elseif ((ord($Str[$i]) & 0xFC) == 0xF8)
$n = 4;# 111110bb
elseif ((ord($Str[$i]) & 0xFE) == 0xFC)
$n = 5;# 1111110b
else
return false;# Does not match any model
for ($j = 0; $j < $n; $j++) { # n bytes matching 10bbbbbb follow ?
if (( ++$i == $length) || ((ord($Str[$i]) & 0xC0) != 0x80))
return false;
}
}
return true;
}
|
php
|
public static function seemsUtf8($Str) { # by bmorel at ssi dot fr
$length = strlen($Str);
for ($i = 0; $i < $length; $i++) {
if (ord($Str[$i]) < 0x80)
continue;# 0bbbbbbb
elseif ((ord($Str[$i]) & 0xE0) == 0xC0)
$n = 1;# 110bbbbb
elseif ((ord($Str[$i]) & 0xF0) == 0xE0)
$n = 2;# 1110bbbb
elseif ((ord($Str[$i]) & 0xF8) == 0xF0)
$n = 3;# 11110bbb
elseif ((ord($Str[$i]) & 0xFC) == 0xF8)
$n = 4;# 111110bb
elseif ((ord($Str[$i]) & 0xFE) == 0xFC)
$n = 5;# 1111110b
else
return false;# Does not match any model
for ($j = 0; $j < $n; $j++) { # n bytes matching 10bbbbbb follow ?
if (( ++$i == $length) || ((ord($Str[$i]) & 0xC0) != 0x80))
return false;
}
}
return true;
}
|
Checks to see if a string is utf8 encoded.
@param string $Str The string to be checked
@return bool True if $Str fits a UTF-8 model, false otherwise.
|
https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Text.php#L163-L187
|
cityware/city-format
|
src/Text.php
|
Text.slugify
|
public static function slugify($title, $length = 200) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
$title = self::removeAccents($title);
if (self::seemsUtf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = self::utf8UriEncode($title, $length);
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
|
php
|
public static function slugify($title, $length = 200) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
$title = self::removeAccents($title);
if (self::seemsUtf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = self::utf8UriEncode($title, $length);
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
|
Sanitizes title, replacing whitespace with dashes.
Limits the output to alphanumeric characters, underscore (_) and dash (-).
Whitespace becomes a dash.
@param string $title The title to be sanitized.
@return string The sanitized title.
|
https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Text.php#L234-L257
|
cityware/city-format
|
src/Text.php
|
Text.slug
|
public static function slug($string, $separator = '-') {
$q_separator = preg_quote($separator, '#');
$code = array(
'&.+?;' => '',
'[^a-z0-9 _-]' => '',
'\s+' => $separator,
'(' . $q_separator . ')+' => $separator
);
$string = strip_tags($string);
foreach ($code as $key => $val) {
$string = preg_replace('#' . $key . '#i', $val, $string);
}
$string = strtolower($string);
return trim($string);
}
|
php
|
public static function slug($string, $separator = '-') {
$q_separator = preg_quote($separator, '#');
$code = array(
'&.+?;' => '',
'[^a-z0-9 _-]' => '',
'\s+' => $separator,
'(' . $q_separator . ')+' => $separator
);
$string = strip_tags($string);
foreach ($code as $key => $val) {
$string = preg_replace('#' . $key . '#i', $val, $string);
}
$string = strtolower($string);
return trim($string);
}
|
Função de tratamento de string para formato de URL Amigavel (SLUG)
@param string $string
@param string $separator
@return string
|
https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Text.php#L265-L282
|
cityware/city-format
|
src/Text.php
|
Text.friendUrl
|
public static function friendUrl($varUrl) {
$varUrl = self::removeAcentos($varUrl);
if (mb_detect_encoding($varUrl) == "UTF-8") {
$varUrl = utf8_decode($varUrl);
}
$invalido = (array) str_split(utf8_decode("ÁáÀàÃãÂâÄäÉéÈèÊêËëÍíÌìÎîÏïÓóÒòÕõÔôÖöÚúÙùÛûÜüÇçÑñÝý& "));
$valido = (array) str_split("AaAaAaAaAaEeEeEeEeIiIiIiIiOoOoOoOoOoUuUuUuUuCcNnYye-");
$varUrl = strtolower(str_replace(array("-----", "----", "---", "--"), array("-", "-", "-", "-"), preg_replace("/[^A-Za-z0-9-]*/", "", str_replace($invalido, $valido, $varUrl))));
return $varUrl;
}
|
php
|
public static function friendUrl($varUrl) {
$varUrl = self::removeAcentos($varUrl);
if (mb_detect_encoding($varUrl) == "UTF-8") {
$varUrl = utf8_decode($varUrl);
}
$invalido = (array) str_split(utf8_decode("ÁáÀàÃãÂâÄäÉéÈèÊêËëÍíÌìÎîÏïÓóÒòÕõÔôÖöÚúÙùÛûÜüÇçÑñÝý& "));
$valido = (array) str_split("AaAaAaAaAaEeEeEeEeIiIiIiIiOoOoOoOoOoUuUuUuUuCcNnYye-");
$varUrl = strtolower(str_replace(array("-----", "----", "---", "--"), array("-", "-", "-", "-"), preg_replace("/[^A-Za-z0-9-]*/", "", str_replace($invalido, $valido, $varUrl))));
return $varUrl;
}
|
Função de tratamento de string para formato de URL Amigavel
@param <string> $varUrl
@return <string>
|
https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Text.php#L289-L299
|
cityware/city-format
|
src/Text.php
|
Text.formataTexto
|
public static function formataTexto($texto) {
$texto = htmlentities($texto, ENT_QUOTES);
$acentos = array('á', 'à', 'ã', 'â', 'ä', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ó', 'ò', 'õ', 'ô', 'ö', 'ú', 'ù', 'û', 'ü', 'ç', 'Á', 'À', 'Ã', 'Â', 'Ä', 'É', 'È', 'Ê', 'Ë', 'Í', 'Ì', 'Î', 'Ï', 'Ó', 'Ò', 'Õ', 'Ô', 'Ö', 'Ú', 'Ù', 'Û', 'Ü', 'Ç', 'ñ', 'Ñ');
$acentos_html = array('á', 'à', 'ã', 'â', 'ä', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ó', 'ò', 'õ', 'ô', 'ö', 'ú', 'ù', 'û', 'ü', 'ç', 'Á', 'À', 'Ã', 'Â', 'Ä', 'É', 'È', 'Ê', 'Ë', 'Í', 'Ì', 'Î', 'Ï', 'Ó', 'Ò', 'Õ', 'Ô', 'Ö', 'Ú', 'Ù', 'Û', 'Ü', 'Ç', 'ñ', 'Ñ');
$retorno = str_replace($acentos, $acentos_html, $texto);
return $retorno;
}
|
php
|
public static function formataTexto($texto) {
$texto = htmlentities($texto, ENT_QUOTES);
$acentos = array('á', 'à', 'ã', 'â', 'ä', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ó', 'ò', 'õ', 'ô', 'ö', 'ú', 'ù', 'û', 'ü', 'ç', 'Á', 'À', 'Ã', 'Â', 'Ä', 'É', 'È', 'Ê', 'Ë', 'Í', 'Ì', 'Î', 'Ï', 'Ó', 'Ò', 'Õ', 'Ô', 'Ö', 'Ú', 'Ù', 'Û', 'Ü', 'Ç', 'ñ', 'Ñ');
$acentos_html = array('á', 'à', 'ã', 'â', 'ä', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ó', 'ò', 'õ', 'ô', 'ö', 'ú', 'ù', 'û', 'ü', 'ç', 'Á', 'À', 'Ã', 'Â', 'Ä', 'É', 'È', 'Ê', 'Ë', 'Í', 'Ì', 'Î', 'Ï', 'Ó', 'Ò', 'Õ', 'Ô', 'Ö', 'Ú', 'Ù', 'Û', 'Ü', 'Ç', 'ñ', 'Ñ');
$retorno = str_replace($acentos, $acentos_html, $texto);
return $retorno;
}
|
Função para conversão de texto e caracteres especiais em HTML
@param <string> $texto
@return <string> $retorno
|
https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Text.php#L306-L313
|
cityware/city-format
|
src/Text.php
|
Text.removeAcentosUtf8
|
public static function removeAcentosUtf8($varTexto) {
$table = array(
'Š' => 'S', 'š' => 's', 'Đ' => 'Dj', 'đ' => 'dj', 'Ž' => 'Z', 'ž' => 'z', 'Č' => 'C', 'č' => 'c', 'Ć' => 'C', 'ć' => 'c',
'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E',
'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O',
'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss',
'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e',
'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o',
'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'ý' => 'y', 'þ' => 'b',
'ÿ' => 'y', 'Ŕ' => 'R', 'ŕ' => 'r', '\'' => '', '´' => '', '`' => '', '"' => '', '§' => 'S', '¢' => 'c'
);
return strtr($varTexto, $table);
}
|
php
|
public static function removeAcentosUtf8($varTexto) {
$table = array(
'Š' => 'S', 'š' => 's', 'Đ' => 'Dj', 'đ' => 'dj', 'Ž' => 'Z', 'ž' => 'z', 'Č' => 'C', 'č' => 'c', 'Ć' => 'C', 'ć' => 'c',
'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E',
'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O',
'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss',
'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e',
'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o',
'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'ý' => 'y', 'þ' => 'b',
'ÿ' => 'y', 'Ŕ' => 'R', 'ŕ' => 'r', '\'' => '', '´' => '', '`' => '', '"' => '', '§' => 'S', '¢' => 'c'
);
return strtr($varTexto, $table);
}
|
Remover os acentos de uma string Utf8
@param string $str
@return string
|
https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Text.php#L355-L368
|
cityware/city-format
|
src/Text.php
|
Text.convertTableName
|
public static function convertTableName($varTable) {
$tables = explode(",", $varTable);
$table = (string) "";
foreach ($tables as $key => $value) {
if (strpos($value, '.') !== false) {
$tableField = explode('.', $value);
$varTable = $tableField[0];
$varTable = str_replace("_", " ", $varTable);
$varTable = ucwords(strtolower($varTable));
$varTable = str_replace(" ", "", $varTable);
$varTable.= '.' . $tableField[1];
} else {
$varTable = $value;
$varTable = str_replace("_", " ", $varTable);
$varTable = ucwords(strtolower($varTable));
$varTable = str_replace(" ", "", $varTable);
}
$table.= $varTable . ', ';
}
return (substr(trim($table), 0, -1));
}
|
php
|
public static function convertTableName($varTable) {
$tables = explode(",", $varTable);
$table = (string) "";
foreach ($tables as $key => $value) {
if (strpos($value, '.') !== false) {
$tableField = explode('.', $value);
$varTable = $tableField[0];
$varTable = str_replace("_", " ", $varTable);
$varTable = ucwords(strtolower($varTable));
$varTable = str_replace(" ", "", $varTable);
$varTable.= '.' . $tableField[1];
} else {
$varTable = $value;
$varTable = str_replace("_", " ", $varTable);
$varTable = ucwords(strtolower($varTable));
$varTable = str_replace(" ", "", $varTable);
}
$table.= $varTable . ', ';
}
return (substr(trim($table), 0, -1));
}
|
Função de tratamento de nomes de tabelas do banco de dados
@param <string> $varTable
@return <string>
|
https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Text.php#L496-L520
|
diatem-net/jin-db
|
src/Db/Database/DbConnexion.php
|
DbConnexion.connectWithPostgreSql
|
public static function connectWithPostgreSql($host, $user, $pass, $port, $dbname)
{
self::$cnxHandler = new PostgreSQL($host, $user, $pass, $port, $dbname);
return self::$cnxHandler->connect();
}
|
php
|
public static function connectWithPostgreSql($host, $user, $pass, $port, $dbname)
{
self::$cnxHandler = new PostgreSQL($host, $user, $pass, $port, $dbname);
return self::$cnxHandler->connect();
}
|
Initialise la connexion sur une Base de données PostgreSQL
@param string $host Url du serveur PostgreSQL
@param string $user Utilisateur de base de données
@param string $pass Password de l'utilisateur
@param integer $port Port utilisé
@param string $dbname Nom de la base de données
@return boolean Succès ou echec de connexion
|
https://github.com/diatem-net/jin-db/blob/075ba3f2d4a49ee1022217e9707083cce1cd64d9/src/Db/Database/DbConnexion.php#L36-L40
|
diatem-net/jin-db
|
src/Db/Database/DbConnexion.php
|
DbConnexion.connectWithMySql
|
public static function connectWithMySql($host, $user, $pass, $port, $dbname)
{
self::$cnxHandler = new MySql($host, $user, $pass, $port, $dbname);
return self::$cnxHandler->connect();
}
|
php
|
public static function connectWithMySql($host, $user, $pass, $port, $dbname)
{
self::$cnxHandler = new MySql($host, $user, $pass, $port, $dbname);
return self::$cnxHandler->connect();
}
|
Initialise la connexion sur une Base de données MySql
@param string $host Url du serveur MySql
@param string $user Utilisateur de base de données
@param string $pass Password de l'utilisateur
@param integer $port Port utilisé
@param string $dbname Nom de la base de données
@return boolean Succès ou echec de connexion
|
https://github.com/diatem-net/jin-db/blob/075ba3f2d4a49ee1022217e9707083cce1cd64d9/src/Db/Database/DbConnexion.php#L52-L56
|
diatem-net/jin-db
|
src/Db/Database/DbConnexion.php
|
DbConnexion.connectWithWordPress
|
public static function connectWithWordPress($rootPath = '/')
{
include_once $rootPath.'wp-config.php';
self::$cnxHandler = new MySql(DB_HOST, DB_USER, DB_PASSWORD, 5432, DB_NAME);
return self::$cnxHandler->connect();
}
|
php
|
public static function connectWithWordPress($rootPath = '/')
{
include_once $rootPath.'wp-config.php';
self::$cnxHandler = new MySql(DB_HOST, DB_USER, DB_PASSWORD, 5432, DB_NAME);
return self::$cnxHandler->connect();
}
|
Initialise automatiquement une connexion sur un site géré avec WordPress
@param string $rootPath Racine du site
@return boolean Succès ou echec de connexion
|
https://github.com/diatem-net/jin-db/blob/075ba3f2d4a49ee1022217e9707083cce1cd64d9/src/Db/Database/DbConnexion.php#L76-L81
|
diatem-net/jin-db
|
src/Db/Database/DbConnexion.php
|
DbConnexion.connectWithPrestashop
|
public static function connectWithPrestashop($rootPath = '/')
{
include_once $rootPath.'config/settings.inc.php';
self::$cnxHandler = new MySql(_DB_SERVER_, _DB_USER_, _DB_PASSWD_, 5432, _DB_NAME_);
return self::$cnxHandler->connect();
}
|
php
|
public static function connectWithPrestashop($rootPath = '/')
{
include_once $rootPath.'config/settings.inc.php';
self::$cnxHandler = new MySql(_DB_SERVER_, _DB_USER_, _DB_PASSWD_, 5432, _DB_NAME_);
return self::$cnxHandler->connect();
}
|
Initialise automatiquement une connexion sur un site géré avec Prestashop
@param string $rootPath Racine du site
@return boolean Succès ou echec de connexion
|
https://github.com/diatem-net/jin-db/blob/075ba3f2d4a49ee1022217e9707083cce1cd64d9/src/Db/Database/DbConnexion.php#L89-L94
|
diatem-net/jin-db
|
src/Db/Database/DbConnexion.php
|
DbConnexion.getLastInsertId
|
public static function getLastInsertId($tableName = null, $cle = null)
{
return self::$cnxHandler->getLastInsertId($tableName, $cle);
}
|
php
|
public static function getLastInsertId($tableName = null, $cle = null)
{
return self::$cnxHandler->getLastInsertId($tableName, $cle);
}
|
Retourne le dernier ID inséré. (Avec MySql les arguments tableName et cle ne sont pas nécessaires)
@param string $tableName Nom de la table
@param string $cle Nom de la clé primaire
|
https://github.com/diatem-net/jin-db/blob/075ba3f2d4a49ee1022217e9707083cce1cd64d9/src/Db/Database/DbConnexion.php#L126-L129
|
headzoo/web-tools
|
src/Headzoo/Web/Tools/WebServer.php
|
WebServer.start
|
public function start($single = true)
{
$this->socket = socket_create(AF_INET, SOCK_STREAM, 0);
if (!$this->socket) {
$err = socket_last_error();
throw new Exceptions\SocketException(
socket_strerror($err),
$err
);
}
/** @noinspection PhpUnusedLocalVariableInspection */
$complete = Complete::factory(function() {
if ($this->socket) {
socket_close($this->socket);
}
});
if (!socket_bind($this->socket, $this->host, $this->port) || !socket_listen($this->socket)) {
$err = socket_last_error();
throw new Exceptions\SocketException(
socket_strerror($err),
$err
);
}
while(true) {
$this->client = socket_accept($this->socket);
if (!$this->client) {
$err = socket_last_error();
throw new Exceptions\SocketException(
socket_strerror($err),
$err
);
}
$input = socket_read($this->client, 2045);
if (false === $input) {
$err = socket_last_error();
throw new Exceptions\SocketException(
socket_strerror($err),
$err
);
}
$headersSent = false;
$parser = $this->getHttpParser();
$request = $parser->parse($input);
$response = "";
try {
if ($this->callback) {
$response = call_user_func($this->callback, $request);
}
if (false === $response || null === $response) {
$response = $this->getFile($request);
}
} catch (Exceptions\HttpStatusError $e) {
$this->sendResponseHeadersToClient(
$request,
$e->getCode(),
$e->getMessage()
);
$headersSent = true;
}
if (!$headersSent) {
$this->sendResponseHeadersToClient($request, 200, "OK");
$this->sendToClient($response);
}
if ($single) {
break;
}
}
}
|
php
|
public function start($single = true)
{
$this->socket = socket_create(AF_INET, SOCK_STREAM, 0);
if (!$this->socket) {
$err = socket_last_error();
throw new Exceptions\SocketException(
socket_strerror($err),
$err
);
}
/** @noinspection PhpUnusedLocalVariableInspection */
$complete = Complete::factory(function() {
if ($this->socket) {
socket_close($this->socket);
}
});
if (!socket_bind($this->socket, $this->host, $this->port) || !socket_listen($this->socket)) {
$err = socket_last_error();
throw new Exceptions\SocketException(
socket_strerror($err),
$err
);
}
while(true) {
$this->client = socket_accept($this->socket);
if (!$this->client) {
$err = socket_last_error();
throw new Exceptions\SocketException(
socket_strerror($err),
$err
);
}
$input = socket_read($this->client, 2045);
if (false === $input) {
$err = socket_last_error();
throw new Exceptions\SocketException(
socket_strerror($err),
$err
);
}
$headersSent = false;
$parser = $this->getHttpParser();
$request = $parser->parse($input);
$response = "";
try {
if ($this->callback) {
$response = call_user_func($this->callback, $request);
}
if (false === $response || null === $response) {
$response = $this->getFile($request);
}
} catch (Exceptions\HttpStatusError $e) {
$this->sendResponseHeadersToClient(
$request,
$e->getCode(),
$e->getMessage()
);
$headersSent = true;
}
if (!$headersSent) {
$this->sendResponseHeadersToClient($request, 200, "OK");
$this->sendToClient($response);
}
if ($single) {
break;
}
}
}
|
{@inheritDoc}
|
https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebServer.php#L145-L219
|
headzoo/web-tools
|
src/Headzoo/Web/Tools/WebServer.php
|
WebServer.sendResponseHeadersToClient
|
protected function sendResponseHeadersToClient(WebRequest $request, $code, $message)
{
$headers = [
"Date" => gmdate("D, d M Y H:i:s T"),
"Connection" => "close"
];
$bytes = $this->sendToClient($request->getVersion() . " {$code} {$message}\r\n");
foreach($headers as $header => $value) {
$bytes += $this->sendToClient("{$header}: {$value}\r\n");
}
$bytes += $this->sendToClient("\r\n");
return $bytes;
}
|
php
|
protected function sendResponseHeadersToClient(WebRequest $request, $code, $message)
{
$headers = [
"Date" => gmdate("D, d M Y H:i:s T"),
"Connection" => "close"
];
$bytes = $this->sendToClient($request->getVersion() . " {$code} {$message}\r\n");
foreach($headers as $header => $value) {
$bytes += $this->sendToClient("{$header}: {$value}\r\n");
}
$bytes += $this->sendToClient("\r\n");
return $bytes;
}
|
Sends the response headers through the client socket
Returns the number of bytes sent.
@param WebRequest $request The http request
@param int $code The http status code to sent
@param string $message The http status message to send
@return int
|
https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebServer.php#L231-L245
|
headzoo/web-tools
|
src/Headzoo/Web/Tools/WebServer.php
|
WebServer.sendToClient
|
protected function sendToClient($line)
{
$bytes = 0;
$len = strlen($line);
if ($len) {
while(true) {
$sent = socket_write($this->client, $line, $len);
if (false === $sent) {
throw new Exceptions\HttpStatusError(
"Internal server error.",
500
);
}
$bytes += $sent;
if ($sent < $len) {
$line = substr($line, $sent);
$len -= $sent;
} else {
break;
}
}
}
return $bytes;
}
|
php
|
protected function sendToClient($line)
{
$bytes = 0;
$len = strlen($line);
if ($len) {
while(true) {
$sent = socket_write($this->client, $line, $len);
if (false === $sent) {
throw new Exceptions\HttpStatusError(
"Internal server error.",
500
);
}
$bytes += $sent;
if ($sent < $len) {
$line = substr($line, $sent);
$len -= $sent;
} else {
break;
}
}
}
return $bytes;
}
|
Sends a string through the client socket
Returns the number of bytes sent.
@param string $line The string to send
@return int
@throws Exceptions\HttpStatusError
|
https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebServer.php#L256-L281
|
headzoo/web-tools
|
src/Headzoo/Web/Tools/WebServer.php
|
WebServer.getFile
|
protected function getFile(WebRequest $request)
{
$path = realpath($this->dirRoot . DIRECTORY_SEPARATOR . $request->getPath());
if (false === $path) {
throw new Exceptions\HttpStatusError(
"File not found.",
404
);
}
if (is_dir($path)) {
$path .= DIRECTORY_SEPARATOR . $this->index;
}
$contents = null;
$info = pathinfo($path);
if ($info["extension"] == "php") {
ob_start();
/** @noinspection PhpIncludeInspection */
include($path);
$contents = ob_get_contents();
ob_end_clean();
} else {
$contents = file_get_contents($path);
}
return $contents;
}
|
php
|
protected function getFile(WebRequest $request)
{
$path = realpath($this->dirRoot . DIRECTORY_SEPARATOR . $request->getPath());
if (false === $path) {
throw new Exceptions\HttpStatusError(
"File not found.",
404
);
}
if (is_dir($path)) {
$path .= DIRECTORY_SEPARATOR . $this->index;
}
$contents = null;
$info = pathinfo($path);
if ($info["extension"] == "php") {
ob_start();
/** @noinspection PhpIncludeInspection */
include($path);
$contents = ob_get_contents();
ob_end_clean();
} else {
$contents = file_get_contents($path);
}
return $contents;
}
|
Returns the data for the requested file
@param WebRequest $request The http request
@return string
@throws Exceptions\HttpStatusError
|
https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebServer.php#L290-L316
|
timostamm/url-builder
|
src/UrlPath.php
|
UrlPath.parseComponent
|
public function parseComponent($str)
{
if (! is_string($str)) {
throw new InvalidUrlException('Unexpected type.');
}
if (strpos($str, ' ') !== false) {
throw new InvalidUrlException('Path contains whitespace.');
}
$p = explode('/', $str);
foreach ($p as $i => $v) {
$p[$i] = rawurldecode($v);
}
$decodedPath = join('/', $p);
$this->path->set($decodedPath);
}
|
php
|
public function parseComponent($str)
{
if (! is_string($str)) {
throw new InvalidUrlException('Unexpected type.');
}
if (strpos($str, ' ') !== false) {
throw new InvalidUrlException('Path contains whitespace.');
}
$p = explode('/', $str);
foreach ($p as $i => $v) {
$p[$i] = rawurldecode($v);
}
$decodedPath = join('/', $p);
$this->path->set($decodedPath);
}
|
Parses a path component as it appears in a URL.
@param string $str
@throws \InvalidArgumentException
|
https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlPath.php#L41-L55
|
timostamm/url-builder
|
src/UrlPath.php
|
UrlPath.get
|
public function get()
{
if (is_null($this->url)) {
return $this->path->get();
}
if (! $this->url->host->isEmpty()) {
return Path::info('/')->resolve($this->path)->get();
}
return $this->path->get();
}
|
php
|
public function get()
{
if (is_null($this->url)) {
return $this->path->get();
}
if (! $this->url->host->isEmpty()) {
return Path::info('/')->resolve($this->path)->get();
}
return $this->path->get();
}
|
Returns the decoded path.
The path will start with a slash if the host is set, regardless whether
the slash was present in the parsed URL and regardless whether you
included the slash when setting the path via set().
Please not that __toString() does not prepend the slash.
@return string
|
https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlPath.php#L68-L77
|
timostamm/url-builder
|
src/UrlPath.php
|
UrlPath.set
|
public function set($str)
{
if ($str instanceof Path) {
$this->path->set($str->get());
} else if ($str instanceof UrlPath) {
$this->path->set($str->get());
} else if (is_string($str)) {
$this->path->set($str);
} else {
throw new \InvalidArgumentException('Unexpected type.');
}
}
|
php
|
public function set($str)
{
if ($str instanceof Path) {
$this->path->set($str->get());
} else if ($str instanceof UrlPath) {
$this->path->set($str->get());
} else if (is_string($str)) {
$this->path->set($str);
} else {
throw new \InvalidArgumentException('Unexpected type.');
}
}
|
Sets the decoded path.
@param string|UrlPath|Path $str
@throws \InvalidArgumentException
|
https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlPath.php#L85-L96
|
timostamm/url-builder
|
src/UrlPath.php
|
UrlPath.isAbsolute
|
public function isAbsolute()
{
if (! is_null($this->url) && $this->path->isEmpty()) {
return ! $this->url->host->isEmpty();
}
return $this->path->isAbsolute();
}
|
php
|
public function isAbsolute()
{
if (! is_null($this->url) && $this->path->isEmpty()) {
return ! $this->url->host->isEmpty();
}
return $this->path->isAbsolute();
}
|
URLs can be relative if scheme and host are omitted.
Examples for relative URLs are:
- ../foo.html
- foo.html
However, they can have an absolute path at the same time:
- /index.html
You can use this method to determine whether the path is absolute or not.
@return boolean
|
https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlPath.php#L135-L141
|
timostamm/url-builder
|
src/UrlPath.php
|
UrlPath.dirname
|
public function dirname()
{
if (! is_null($this->url) && $this->path->isEmpty() && ! $this->url->host->isEmpty()) {
return '/';
}
return $this->path->dirname();
}
|
php
|
public function dirname()
{
if (! is_null($this->url) && $this->path->isEmpty() && ! $this->url->host->isEmpty()) {
return '/';
}
return $this->path->dirname();
}
|
Return the path excluding the filename.
If the URL has a host but no path, we still return '/'.
@return string
|
https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlPath.php#L160-L166
|
chilimatic/chilimatic-framework
|
lib/config/Node.php
|
Node.initType
|
private function initType($data)
{
if (!is_string($data)) return false;
$data = trim($data);
switch (true) {
case (in_array($data, ['true', 'false'])):
$this->data = (bool)(strpos($data, 'true') !== false) ? true : false;
break;
case !is_numeric($data):
if ($res = json_decode($data)) {
$this->data = $res;
} else if (($res = @unserialize($data)) !== false) {
$this->data = $res;
} else if ((preg_match('/^["|\']{1}(.*)["|\']{1}$/', $data, $match)) === 1) {
$this->data = (string)$match[1];
} else {
$this->data = (string)$data;
}
break;
default:
// integer
if (is_numeric($data) && strpos($data, '.') === false) {
$this->data = (int)$data;
} else {
$this->data = (float)$data;
}
break;
}
return true;
}
|
php
|
private function initType($data)
{
if (!is_string($data)) return false;
$data = trim($data);
switch (true) {
case (in_array($data, ['true', 'false'])):
$this->data = (bool)(strpos($data, 'true') !== false) ? true : false;
break;
case !is_numeric($data):
if ($res = json_decode($data)) {
$this->data = $res;
} else if (($res = @unserialize($data)) !== false) {
$this->data = $res;
} else if ((preg_match('/^["|\']{1}(.*)["|\']{1}$/', $data, $match)) === 1) {
$this->data = (string)$match[1];
} else {
$this->data = (string)$data;
}
break;
default:
// integer
if (is_numeric($data) && strpos($data, '.') === false) {
$this->data = (int)$data;
} else {
$this->data = (float)$data;
}
break;
}
return true;
}
|
method to set the current type and initializes it
@param $data
@return bool
|
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/config/Node.php#L69-L101
|
3ev/wordpress-core
|
src/Tev/Field/Model/ImageField.php
|
ImageField.sizeUrl
|
public function sizeUrl($size)
{
if (($this->base['return_format'] === 'array') && isset($this->base['value']['sizes'][$size])) {
return $this->base['value']['sizes'][$size];
} elseif ($this->base['return_format'] === 'id') {
if ($src = wp_get_attachment_image_src($this->id(), $size)) {
return $src[0];
}
}
return '';
}
|
php
|
public function sizeUrl($size)
{
if (($this->base['return_format'] === 'array') && isset($this->base['value']['sizes'][$size])) {
return $this->base['value']['sizes'][$size];
} elseif ($this->base['return_format'] === 'id') {
if ($src = wp_get_attachment_image_src($this->id(), $size)) {
return $src[0];
}
}
return '';
}
|
Get an image URL of a specic size.
@param string $size Image size (e.g thumbnail, large or custom size)
@return string Image URL
|
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Model/ImageField.php#L86-L97
|
3ev/wordpress-core
|
src/Tev/Field/Model/ImageField.php
|
ImageField.normalize
|
protected function normalize()
{
parent::normalize();
$val = $this->base['value'];
if ($val) {
switch ($this->base['return_format']) {
case 'array':
$this->atWidth = $val['width'];
$this->atHeight = $val['height'];
break;
case 'id':
$src = wp_get_attachment_image_src($this->id(), 'full');
$this->atWidth = $src[1];
$this->atHeight = $src[2];
break;
case 'url':
$this->atWidth = 0;
$this->atHeight = 0;
break;
default:
throw new Exception("Field format {$this->base['return_format']} not valid");
}
} else {
$this->atWidth = 0;
$this->atHeight = 0;
}
}
|
php
|
protected function normalize()
{
parent::normalize();
$val = $this->base['value'];
if ($val) {
switch ($this->base['return_format']) {
case 'array':
$this->atWidth = $val['width'];
$this->atHeight = $val['height'];
break;
case 'id':
$src = wp_get_attachment_image_src($this->id(), 'full');
$this->atWidth = $src[1];
$this->atHeight = $src[2];
break;
case 'url':
$this->atWidth = 0;
$this->atHeight = 0;
break;
default:
throw new Exception("Field format {$this->base['return_format']} not valid");
}
} else {
$this->atWidth = 0;
$this->atHeight = 0;
}
}
|
{@inheritDoc}
|
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Model/ImageField.php#L102-L134
|
CampaignChain/core-esp
|
Service/BusinessRule.php
|
BusinessRule.execute
|
public function execute(array $expressions)
{
$sum = 0;
$exprLang = new ExpressionLanguage();
foreach($expressions as $node => $clauses) {
$value = NULL;
if ($node != 'event'){
EventValidator::isValidPropertyPath($node);
// Get the value of the array node.
eval(
'if(isset($this->data["properties"]' . $node . ') && !empty($this->data["properties"]' . $node . ')){'
. '$value = $this->data["properties"]' . $node . ';'
. '}'
);
}
if($value == NULL && $node != 'event') {
return $sum;
}
// Evaluate the clause and assign points accordingly.
$result = 0;
foreach ($clauses as $clause) {
$result = (int)$exprLang->evaluate(
$clause, array(
'value' => $value,
'relationships' => $this->data['relationships'],
));
if($result != 0) {
$sum = $sum + $result;
break;
}
}
}
return $sum;
}
|
php
|
public function execute(array $expressions)
{
$sum = 0;
$exprLang = new ExpressionLanguage();
foreach($expressions as $node => $clauses) {
$value = NULL;
if ($node != 'event'){
EventValidator::isValidPropertyPath($node);
// Get the value of the array node.
eval(
'if(isset($this->data["properties"]' . $node . ') && !empty($this->data["properties"]' . $node . ')){'
. '$value = $this->data["properties"]' . $node . ';'
. '}'
);
}
if($value == NULL && $node != 'event') {
return $sum;
}
// Evaluate the clause and assign points accordingly.
$result = 0;
foreach ($clauses as $clause) {
$result = (int)$exprLang->evaluate(
$clause, array(
'value' => $value,
'relationships' => $this->data['relationships'],
));
if($result != 0) {
$sum = $sum + $result;
break;
}
}
}
return $sum;
}
|
Expressions to be provided in the following forward as per below
example:
@param array $expressions
@return int
|
https://github.com/CampaignChain/core-esp/blob/21a946295e5d68e2cf42dbcc63edb84433793d04/Service/BusinessRule.php#L54-L94
|
SpoonX/SxBootstrap
|
src/SxBootstrap/View/Helper/Bootstrap/Tooltip.php
|
Tooltip.setOption
|
public function setOption($key, $value)
{
if (!in_array($key, $this->availableOptions)) {
throw new Exception\InvalidArgumentException('Invalid option for Tooltip');
}
if (is_bool($value)) {
$value = $value ? 'true' : 'false';
}
if (!is_string($value)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid value for Tooltip, expected boolean or string, got "%s"',
gettype($value)
));
}
$this->getElement()->addAttribute("data-$key", $value);
return $this;
}
|
php
|
public function setOption($key, $value)
{
if (!in_array($key, $this->availableOptions)) {
throw new Exception\InvalidArgumentException('Invalid option for Tooltip');
}
if (is_bool($value)) {
$value = $value ? 'true' : 'false';
}
if (!is_string($value)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid value for Tooltip, expected boolean or string, got "%s"',
gettype($value)
));
}
$this->getElement()->addAttribute("data-$key", $value);
return $this;
}
|
Set a single option to the Tooltip
@param string $key
@param string $value
@return \SxBootstrap\View\Helper\Bootstrap\Label
@throws Exception\InvalidArgumentException
|
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Tooltip.php#L145-L165
|
phOnion/framework
|
src/Http/Header/Accept.php
|
Accept.supports
|
public function supports(string $contentType): bool
{
foreach (array_keys($this->types) as $pattern) {
$pattern = str_replace(['*', '.', '/', '+'], ['(.*)', '.', '\/', '\+'], $pattern);
if (preg_match("#^$pattern$#i", $contentType) > 0) {
return true;
}
}
return false;
}
|
php
|
public function supports(string $contentType): bool
{
foreach (array_keys($this->types) as $pattern) {
$pattern = str_replace(['*', '.', '/', '+'], ['(.*)', '.', '\/', '\+'], $pattern);
if (preg_match("#^$pattern$#i", $contentType) > 0) {
return true;
}
}
return false;
}
|
Check whether or not the current content-type
is supported by the client. Not that this
checks as-is and does not try to determine
if `application/*` is supported for example
@param string $contentType
@return bool
|
https://github.com/phOnion/framework/blob/eb2d99cc65d3b39faecbfd49b602fb2c62349d05/src/Http/Header/Accept.php#L61-L70
|
phOnion/framework
|
src/Http/Header/Accept.php
|
Accept.getPriority
|
public function getPriority(string $contentType): float
{
foreach ($this->types as $pattern => $weight) {
$pattern = str_replace(['*', '.', '/', '+'], ['(.*)', '.', '\/', '\+'], $pattern);
if (preg_match("#^$pattern$#i", $contentType) > 0) {
return $weight;
}
}
return -1.0;
}
|
php
|
public function getPriority(string $contentType): float
{
foreach ($this->types as $pattern => $weight) {
$pattern = str_replace(['*', '.', '/', '+'], ['(.*)', '.', '\/', '\+'], $pattern);
if (preg_match("#^$pattern$#i", $contentType) > 0) {
return $weight;
}
}
return -1.0;
}
|
Retrieves the 'weight' of the $contentType provided.
@param string $contentType
@return float
|
https://github.com/phOnion/framework/blob/eb2d99cc65d3b39faecbfd49b602fb2c62349d05/src/Http/Header/Accept.php#L78-L88
|
andyburton/Sonic-Framework
|
src/ExtJS.php
|
ExtJS._getGrid
|
public static function _getGrid ($class, $params = array ())
{
// If the class doesn't exist
if (!class_exists ($class))
{
throw new Exception ('Class does not exist: ' . $class);
}
// If the class doesn't extend the model
if (!array_key_exists ('Sonic\Model', class_parents ($class)))
{
throw new Exception ('Class ' . $class . ' must extend \Sonic\Model');
}
// If no limit has been set
if (!$params || !isset ($params['limit']))
{
// Set default query limit
$params['limit'] = array (0, 50);
}
// Get data
$data = $class::_getValues ($params);
// Get count
$count = $class::_Count ($params);
// Set result array
if (FALSE !== $count && FALSE !== $data)
{
// Set result
$result = array (
'success' => TRUE,
'total' => $count,
'rows' => $data
);
}
else
{
// Set error JSON
$result = array (
'success' => FALSE,
'total' => '0',
'rows' => array (),
'msg' => Message::getString ('error')
);
}
// Return result
return $result;
}
|
php
|
public static function _getGrid ($class, $params = array ())
{
// If the class doesn't exist
if (!class_exists ($class))
{
throw new Exception ('Class does not exist: ' . $class);
}
// If the class doesn't extend the model
if (!array_key_exists ('Sonic\Model', class_parents ($class)))
{
throw new Exception ('Class ' . $class . ' must extend \Sonic\Model');
}
// If no limit has been set
if (!$params || !isset ($params['limit']))
{
// Set default query limit
$params['limit'] = array (0, 50);
}
// Get data
$data = $class::_getValues ($params);
// Get count
$count = $class::_Count ($params);
// Set result array
if (FALSE !== $count && FALSE !== $data)
{
// Set result
$result = array (
'success' => TRUE,
'total' => $count,
'rows' => $data
);
}
else
{
// Set error JSON
$result = array (
'success' => FALSE,
'total' => '0',
'rows' => array (),
'msg' => Message::getString ('error')
);
}
// Return result
return $result;
}
|
Return an array for use in an Ext grid in the format:
array(
'success' => true/false,
'total' => total number of rows,
'rows' => array of results
'msg' => error message if success is false
)
@param string $class Model class name of data to return
@param array $params Array of query parameters - MUST BE ESCAPED!
@return array
|
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/ExtJS.php#L30-L98
|
zara-4/php-sdk
|
Zara4/API/Communication/Util.php
|
Util.handleError
|
private static function handleError($responseData) {
$error = $responseData->{'error'};
$data = array_key_exists('data', $responseData) ? $responseData->{'data'} : null;
// --- --- --
//
// OAuth
//
// Client does not have scope permission
if ($error == 'invalid_scope') {
throw new AccessDeniedException('The client credentials are not authorised to perform this action. Scope error.');
}
// --- --- ---
//
// Image Processing
//
// Quota limit
if ($error == 'quota_limit') {
$action = $data && array_key_exists('maximum-webhooks', $data)
? $data->{'action'} : 'registration-required';
if ($action == 'registration-required') {
throw new AnonymousUserQuotaLimitException();
} else {
throw new RegisteredUserQuotaLimitException();
}
}
// --- --- ---
//
// User
//
// Email not verified
if ($responseData->{'error'} == 'user_email_not_verified') {
throw new EmailNotVerifiedException($responseData->{'error_description'});
}
// --- --- ---
//
// Billing
//
// Bad payment
if ($error == 'bad_payment') {
throw new BadPaymentException($responseData->{'error_description'});
}
// --- --- --
//
// Webhooks
//
// Webhook limit reached
if ($responseData->{'error'} == 'webhook_limit_reached') {
$maximumWebhooks = $data && array_key_exists('maximum-webhooks', $data)
? $data->{'maximum-webhooks'} : 10;
throw new WebhookLimitReachedException($maximumWebhooks);
}
// --- --- ---
//
// Cloud
//
// Invalid AWS credentials
if ($error == 'cloud_aws_invalid_credentials') {
throw new InvalidCredentialsException();
}
// Invalid AWS S3 Bucket
if ($error == 'cloud_aws_invalid_bucket') {
$bucket = array_key_exists('bucket', $data) ? $data->{'bucket'} : null;
throw new InvalidBucketException($bucket);
}
// --- --- ---
//
// Account Registration
//
// Recaptcha invalid
if ($error == 'auth_register_invalid-recaptcha') {
throw new InvalidRecaptchaException();
}
// Email address domain is blacklisted
if ($error == 'auth_register_email-domain-blacklisted') {
$domain = array_key_exists('domain', $data) ? $data->{'domain'} : null;
throw new DomainIsBlacklistedException($domain);
}
// Email address is already in use
if ($error == 'auth_register_email-already-in-use') {
throw new EmailAlreadyInUseException();
}
// Password too short
if ($error == 'auth_register_password-too-short') {
$minimumLength = array_key_exists('minimum-length', $data) ? $data->{'minimum-length'} : null;
throw new PasswordTooShortException($minimumLength);
}
// Name invalid
if ($error == 'auth_register_invalid-name') {
throw new InvalidNameException();
}
// --- --- ---
// Generic error
throw new UnknownException($responseData->{'error_description'});
}
|
php
|
private static function handleError($responseData) {
$error = $responseData->{'error'};
$data = array_key_exists('data', $responseData) ? $responseData->{'data'} : null;
// --- --- --
//
// OAuth
//
// Client does not have scope permission
if ($error == 'invalid_scope') {
throw new AccessDeniedException('The client credentials are not authorised to perform this action. Scope error.');
}
// --- --- ---
//
// Image Processing
//
// Quota limit
if ($error == 'quota_limit') {
$action = $data && array_key_exists('maximum-webhooks', $data)
? $data->{'action'} : 'registration-required';
if ($action == 'registration-required') {
throw new AnonymousUserQuotaLimitException();
} else {
throw new RegisteredUserQuotaLimitException();
}
}
// --- --- ---
//
// User
//
// Email not verified
if ($responseData->{'error'} == 'user_email_not_verified') {
throw new EmailNotVerifiedException($responseData->{'error_description'});
}
// --- --- ---
//
// Billing
//
// Bad payment
if ($error == 'bad_payment') {
throw new BadPaymentException($responseData->{'error_description'});
}
// --- --- --
//
// Webhooks
//
// Webhook limit reached
if ($responseData->{'error'} == 'webhook_limit_reached') {
$maximumWebhooks = $data && array_key_exists('maximum-webhooks', $data)
? $data->{'maximum-webhooks'} : 10;
throw new WebhookLimitReachedException($maximumWebhooks);
}
// --- --- ---
//
// Cloud
//
// Invalid AWS credentials
if ($error == 'cloud_aws_invalid_credentials') {
throw new InvalidCredentialsException();
}
// Invalid AWS S3 Bucket
if ($error == 'cloud_aws_invalid_bucket') {
$bucket = array_key_exists('bucket', $data) ? $data->{'bucket'} : null;
throw new InvalidBucketException($bucket);
}
// --- --- ---
//
// Account Registration
//
// Recaptcha invalid
if ($error == 'auth_register_invalid-recaptcha') {
throw new InvalidRecaptchaException();
}
// Email address domain is blacklisted
if ($error == 'auth_register_email-domain-blacklisted') {
$domain = array_key_exists('domain', $data) ? $data->{'domain'} : null;
throw new DomainIsBlacklistedException($domain);
}
// Email address is already in use
if ($error == 'auth_register_email-already-in-use') {
throw new EmailAlreadyInUseException();
}
// Password too short
if ($error == 'auth_register_password-too-short') {
$minimumLength = array_key_exists('minimum-length', $data) ? $data->{'minimum-length'} : null;
throw new PasswordTooShortException($minimumLength);
}
// Name invalid
if ($error == 'auth_register_invalid-name') {
throw new InvalidNameException();
}
// --- --- ---
// Generic error
throw new UnknownException($responseData->{'error_description'});
}
|
Handle error
@param $responseData
@throws AccessDeniedException
@throws \Zara4\API\ImageProcessing\EmailNotVerifiedException
@throws WebhookLimitReachedException
@throws \Zara4\API\ImageProcessing\RegisteredUserQuotaLimitException
@throws UnknownException
@throws \Zara4\API\ImageProcessing\AnonymousUserQuotaLimitException
@throws \Zara4\API\CloudStorage\AwsS3\InvalidCredentialsException
@throws \Zara4\API\CloudStorage\AwsS3\InvalidBucketException
@throws BadPaymentException
|
https://github.com/zara-4/php-sdk/blob/33a1bc9676d9d870a0e274ca44068b207e5dae78/Zara4/API/Communication/Util.php#L44-L166
|
zara-4/php-sdk
|
Zara4/API/Communication/Util.php
|
Util.get
|
public static function get($url, $data) {
//
// Attempt Request
//
try {
$client = new Client();
$res = $client->get($url, $data);
return json_decode($res->getBody());
}
//
// Error Handling
//
catch (RequestException $e) {
$responseData = json_decode($e->getResponse()->getBody());
self::handleError($responseData);
throw new \Zara4\API\Exception();
}
}
|
php
|
public static function get($url, $data) {
//
// Attempt Request
//
try {
$client = new Client();
$res = $client->get($url, $data);
return json_decode($res->getBody());
}
//
// Error Handling
//
catch (RequestException $e) {
$responseData = json_decode($e->getResponse()->getBody());
self::handleError($responseData);
throw new \Zara4\API\Exception();
}
}
|
GET the given $data to the given $url.
@param $url
@param $data
@throws \Zara4\API\Exception
@return array
|
https://github.com/zara-4/php-sdk/blob/33a1bc9676d9d870a0e274ca44068b207e5dae78/Zara4/API/Communication/Util.php#L177-L196
|
zara-4/php-sdk
|
Zara4/API/Communication/Util.php
|
Util.currentIpAddress
|
public static function currentIpAddress() {
//
// Just get the headers if we can or else use the SERVER global
//
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
} else {
$headers = $_SERVER;
}
//
// Get the forwarded IP if it exists
//
if (
array_key_exists('X-Forwarded-For', $headers) &&
filter_var($headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
) {
$the_ip = $headers['X-Forwarded-For'];
}
elseif (
array_key_exists('HTTP_X_FORWARDED_FOR', $headers ) &&
filter_var($headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
) {
$the_ip = $headers['HTTP_X_FORWARDED_FOR'];
}
else {
$the_ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
}
return $the_ip;
}
|
php
|
public static function currentIpAddress() {
//
// Just get the headers if we can or else use the SERVER global
//
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
} else {
$headers = $_SERVER;
}
//
// Get the forwarded IP if it exists
//
if (
array_key_exists('X-Forwarded-For', $headers) &&
filter_var($headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
) {
$the_ip = $headers['X-Forwarded-For'];
}
elseif (
array_key_exists('HTTP_X_FORWARDED_FOR', $headers ) &&
filter_var($headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
) {
$the_ip = $headers['HTTP_X_FORWARDED_FOR'];
}
else {
$the_ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
}
return $the_ip;
}
|
Get the ip address from the current request.
@return String
|
https://github.com/zara-4/php-sdk/blob/33a1bc9676d9d870a0e274ca44068b207e5dae78/Zara4/API/Communication/Util.php#L266-L299
|
openclerk/users
|
src/GoogleWithOpenID.php
|
GoogleWithOpenID.safe_base64_decode
|
public static function safe_base64_decode($input) {
$remainder = strlen($input) % 4;
if ($remainder) {
$padlen = 4 - $remainder;
$input .= str_repeat('=', $padlen);
}
return base64_decode(strtr($input, '-_', '+/'));
}
|
php
|
public static function safe_base64_decode($input) {
$remainder = strlen($input) % 4;
if ($remainder) {
$padlen = 4 - $remainder;
$input .= str_repeat('=', $padlen);
}
return base64_decode(strtr($input, '-_', '+/'));
}
|
Decode a string with URL-safe Base64.
@param string $input A Base64 encoded string
@return string A decoded string
|
https://github.com/openclerk/users/blob/550c7610c154a2f6655ce65a2df377ccb207bc6d/src/GoogleWithOpenID.php#L26-L33
|
kokspflanze/ZfcTicketSystem
|
src/Service/Category.php
|
Category.getCategory4Id
|
public function getCategory4Id($categoryId)
{
/** @var \ZfcTicketSystem\Entity\Repository\TicketCategory $repository */
$repository = $this->getEntityManager()->getRepository($this->getEntityOptions()->getTicketCategory());
return $repository->getCategory4Id($categoryId);
}
|
php
|
public function getCategory4Id($categoryId)
{
/** @var \ZfcTicketSystem\Entity\Repository\TicketCategory $repository */
$repository = $this->getEntityManager()->getRepository($this->getEntityOptions()->getTicketCategory());
return $repository->getCategory4Id($categoryId);
}
|
@param $categoryId
@return null|\ZfcTicketSystem\Entity\TicketCategory
|
https://github.com/kokspflanze/ZfcTicketSystem/blob/d7cdbf48b12a5e5cf6a2bd3ca545b2fe65fc57e0/src/Service/Category.php#L71-L76
|
schpill/thin
|
src/Navigation/Page.php
|
Page.factory
|
public static function factory($options)
{
if (!is_array($options)) {
throw new Exception(
'Invalid argument: $options must be an array');
}
if (isset($options['type'])) {
$type = $options['type'];
} elseif(self::getDefaultPageType()!= null) {
$type = self::getDefaultPageType();
}
if(isset($type)) {
if (is_string($type) && !empty($type)) {
switch (strtolower($type)) {
case 'mvc':
$type = '\\Thin\\Navigation\\Page\\Mvc';
break;
case 'uri':
$type = '\\Thin\\Navigation\\Page\\Uri';
break;
}
$page = new $type($options);
if (!$page instanceof Page) {
throw new Exception(sprintf(
'Invalid argument: Detected type "%s", which ' .
'is not an instance of Page',
$type));
}
return $page;
}
}
$hasUri = isset($options['uri']);
$hasMvc = isset($options['action']) || isset($options['controller']) ||
isset($options['module']) || isset($options['route']) ||
isset($options['params']);
if ($hasMvc) {
return new Page\Mvc($options);
} elseif ($hasUri) {
return new Page\Uri($options);
} else {
$message = 'Invalid argument: Unable to determine class to instantiate';
if (isset($options['label'])) {
$message .= ' (Page label: ' . $options['label'] . ')';
}
throw new Exception($message);
}
}
|
php
|
public static function factory($options)
{
if (!is_array($options)) {
throw new Exception(
'Invalid argument: $options must be an array');
}
if (isset($options['type'])) {
$type = $options['type'];
} elseif(self::getDefaultPageType()!= null) {
$type = self::getDefaultPageType();
}
if(isset($type)) {
if (is_string($type) && !empty($type)) {
switch (strtolower($type)) {
case 'mvc':
$type = '\\Thin\\Navigation\\Page\\Mvc';
break;
case 'uri':
$type = '\\Thin\\Navigation\\Page\\Uri';
break;
}
$page = new $type($options);
if (!$page instanceof Page) {
throw new Exception(sprintf(
'Invalid argument: Detected type "%s", which ' .
'is not an instance of Page',
$type));
}
return $page;
}
}
$hasUri = isset($options['uri']);
$hasMvc = isset($options['action']) || isset($options['controller']) ||
isset($options['module']) || isset($options['route']) ||
isset($options['params']);
if ($hasMvc) {
return new Page\Mvc($options);
} elseif ($hasUri) {
return new Page\Uri($options);
} else {
$message = 'Invalid argument: Unable to determine class to instantiate';
if (isset($options['label'])) {
$message .= ' (Page label: ' . $options['label'] . ')';
}
throw new Exception($message);
}
}
|
Initialization:
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L150-L204
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setLabel
|
public function setLabel($label)
{
if (null !== $label && !is_string($label)) {
throw new Exception(
'Invalid argument: $label must be a string or null');
}
$this->_label = $label;
return $this;
}
|
php
|
public function setLabel($label)
{
if (null !== $label && !is_string($label)) {
throw new Exception(
'Invalid argument: $label must be a string or null');
}
$this->_label = $label;
return $this;
}
|
Sets page label
@param string $label new page label
@return Page fluent interface, returns self
@throws Exception if empty/no string is given
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L262-L271
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setFragment
|
public function setFragment($fragment)
{
if (null !== $fragment && !is_string($fragment)) {
throw new Exception(
'Invalid argument: $fragment must be a string or null');
}
$this->_fragment = $fragment;
return $this;
}
|
php
|
public function setFragment($fragment)
{
if (null !== $fragment && !is_string($fragment)) {
throw new Exception(
'Invalid argument: $fragment must be a string or null');
}
$this->_fragment = $fragment;
return $this;
}
|
Sets a fragment identifier
@param string $fragment new fragment identifier
@return Page fluent interface, returns self
@throws Exception if empty/no string is given
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L290-L299
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setId
|
public function setId($id = null)
{
if (null !== $id && !is_string($id) && !is_numeric($id)) {
throw new Exception(
'Invalid argument: $id must be a string, number or null');
}
$this->_id = null === $id ? $id : (string) $id;
return $this;
}
|
php
|
public function setId($id = null)
{
if (null !== $id && !is_string($id) && !is_numeric($id)) {
throw new Exception(
'Invalid argument: $id must be a string, number or null');
}
$this->_id = null === $id ? $id : (string) $id;
return $this;
}
|
Sets page id
@param string|null $id [optional] id to set. Default is null,
which sets no id.
@return Page fluent interface, returns self
@throws Exception if not given string or null
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L319-L329
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setTitle
|
public function setTitle($title = null)
{
if (null !== $title && !is_string($title)) {
throw new Exception(
'Invalid argument: $title must be a non-empty string');
}
$this->_title = $title;
return $this;
}
|
php
|
public function setTitle($title = null)
{
if (null !== $title && !is_string($title)) {
throw new Exception(
'Invalid argument: $title must be a non-empty string');
}
$this->_title = $title;
return $this;
}
|
Sets page title
@param string $title [optional] page title. Default is
null, which sets no title.
@return Page fluent interface, returns self
@throws Exception if not given string or null
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L379-L389
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setTarget
|
public function setTarget($target = null)
{
if (null !== $target && !is_string($target)) {
throw new Exception(
'Invalid argument: $target must be a string or null');
}
$this->_target = $target;
return $this;
}
|
php
|
public function setTarget($target = null)
{
if (null !== $target && !is_string($target)) {
throw new Exception(
'Invalid argument: $target must be a string or null');
}
$this->_target = $target;
return $this;
}
|
Sets page target
@param string|null $target [optional] target to set. Default is
null, which sets no target.
@return Page fluent interface, returns self
@throws Exception if target is not string or null
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L409-L419
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setAccesskey
|
public function setAccesskey($character = null)
{
if (null !== $character
&& (!is_string($character) || 1 != strlen($character)))
{
throw new Exception(
'Invalid argument: $character must be a single character or null'
);
}
$this->_accesskey = $character;
return $this;
}
|
php
|
public function setAccesskey($character = null)
{
if (null !== $character
&& (!is_string($character) || 1 != strlen($character)))
{
throw new Exception(
'Invalid argument: $character must be a single character or null'
);
}
$this->_accesskey = $character;
return $this;
}
|
Sets access key for this page
@param string|null $character [optional] access key to set. Default
is null, which sets no access key.
@return Page fluent interface, returns self
@throws Exception if access key is not string or null or
if the string length not equal to one
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L440-L453
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setRel
|
public function setRel($relations = null)
{
$this->_rel = array();
if (null !== $relations) {
if (!is_array($relations)) {
throw new Exception(
'Invalid argument: $relations must be an array');
}
foreach ($relations as $name => $relation) {
if (is_string($name)) {
$this->_rel[$name] = $relation;
}
}
}
return $this;
}
|
php
|
public function setRel($relations = null)
{
$this->_rel = array();
if (null !== $relations) {
if (!is_array($relations)) {
throw new Exception(
'Invalid argument: $relations must be an array');
}
foreach ($relations as $name => $relation) {
if (is_string($name)) {
$this->_rel[$name] = $relation;
}
}
}
return $this;
}
|
Sets the page's forward links to other pages
This method expects an associative array of forward links to other pages,
where each element's key is the name of the relation (e.g. alternate,
prev, next, help, etc), and the value is a mixed value that could somehow
be considered a page.
@param array $relations [optional] an associative array of
forward links to other pages
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L477-L496
|
schpill/thin
|
src/Navigation/Page.php
|
Page.getRel
|
public function getRel($relation = null)
{
if (null !== $relation) {
return isset($this->_rel[$relation]) ?
$this->_rel[$relation] :
null;
}
return $this->_rel;
}
|
php
|
public function getRel($relation = null)
{
if (null !== $relation) {
return isset($this->_rel[$relation]) ?
$this->_rel[$relation] :
null;
}
return $this->_rel;
}
|
Returns the page's forward links to other pages
This method returns an associative array of forward links to other pages,
where each element's key is the name of the relation (e.g. alternate,
prev, next, help, etc), and the value is a mixed value that could somehow
be considered a page.
@param string $relation [optional] name of relation to return. If not
given, all relations will be returned.
@return array an array of relations. If $relation is not
specified, all relations will be returned in
an associative array.
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L512-L521
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setRev
|
public function setRev($relations = null)
{
$this->_rev = array();
if (null !== $relations) {
if (!is_array($relations)) {
throw new Exception(
'Invalid argument: $relations must be an array');
}
foreach ($relations as $name => $relation) {
if (is_string($name)) {
$this->_rev[$name] = $relation;
}
}
}
return $this;
}
|
php
|
public function setRev($relations = null)
{
$this->_rev = array();
if (null !== $relations) {
if (!is_array($relations)) {
throw new Exception(
'Invalid argument: $relations must be an array');
}
foreach ($relations as $name => $relation) {
if (is_string($name)) {
$this->_rev[$name] = $relation;
}
}
}
return $this;
}
|
Sets the page's reverse links to other pages
This method expects an associative array of reverse links to other pages,
where each element's key is the name of the relation (e.g. alternate,
prev, next, help, etc), and the value is a mixed value that could somehow
be considered a page.
@param array $relations [optional] an associative array of
reverse links to other pages
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L535-L553
|
schpill/thin
|
src/Navigation/Page.php
|
Page.getRev
|
public function getRev($relation = null)
{
if (null !== $relation) {
return isset($this->_rev[$relation]) ?
$this->_rev[$relation] :
null;
}
return $this->_rev;
}
|
php
|
public function getRev($relation = null)
{
if (null !== $relation) {
return isset($this->_rev[$relation]) ?
$this->_rev[$relation] :
null;
}
return $this->_rev;
}
|
Returns the page's reverse links to other pages
This method returns an associative array of forward links to other pages,
where each element's key is the name of the relation (e.g. alternate,
prev, next, help, etc), and the value is a mixed value that could somehow
be considered a page.
@param string $relation [optional] name of relation to return. If not
given, all relations will be returned.
@return array an array of relations. If $relation is not
specified, all relations will be returned in
an associative array.
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L569-L578
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setCustomHtmlAttrib
|
public function setCustomHtmlAttrib($name, $value)
{
if (!is_string($name)) {
throw new Exception(
'Invalid argument: $name must be a string'
);
}
if (null !== $value && !is_string($value)) {
throw new Exception(
'Invalid argument: $value must be a string or null'
);
}
if (null === $value && isset($this->_customHtmlAttribs[$name])) {
unset($this->_customHtmlAttribs[$name]);
} else {
$this->_customHtmlAttribs[$name] = $value;
}
return $this;
}
|
php
|
public function setCustomHtmlAttrib($name, $value)
{
if (!is_string($name)) {
throw new Exception(
'Invalid argument: $name must be a string'
);
}
if (null !== $value && !is_string($value)) {
throw new Exception(
'Invalid argument: $value must be a string or null'
);
}
if (null === $value && isset($this->_customHtmlAttribs[$name])) {
unset($this->_customHtmlAttribs[$name]);
} else {
$this->_customHtmlAttribs[$name] = $value;
}
return $this;
}
|
Sets a single custom HTML attribute
@param string $name name of the HTML attribute
@param string|null $value value for the HTML attribute
@return Page fluent interface, returns self
@throws Exception if name is not string or value is
not null or a string
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L589-L610
|
schpill/thin
|
src/Navigation/Page.php
|
Page.getCustomHtmlAttrib
|
public function getCustomHtmlAttrib($name)
{
if (!is_string($name)) {
throw new Exception(
'Invalid argument: $name must be a string'
);
}
if (isset($this->_customHtmlAttribs[$name])) {
return $this->_customHtmlAttribs[$name];
}
return null;
}
|
php
|
public function getCustomHtmlAttrib($name)
{
if (!is_string($name)) {
throw new Exception(
'Invalid argument: $name must be a string'
);
}
if (isset($this->_customHtmlAttribs[$name])) {
return $this->_customHtmlAttribs[$name];
}
return null;
}
|
Returns a single custom HTML attributes by name
@param string $name name of the HTML attribute
@return string|null value for the HTML attribute or null
@throws Exception if name is not string
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L619-L632
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setCustomHtmlAttribs
|
public function setCustomHtmlAttribs(array $attribs)
{
foreach ($attribs as $key => $value) {
$this->setCustomHtmlAttrib($key, $value);
}
return $this;
}
|
php
|
public function setCustomHtmlAttribs(array $attribs)
{
foreach ($attribs as $key => $value) {
$this->setCustomHtmlAttrib($key, $value);
}
return $this;
}
|
Sets multiple custom HTML attributes at once
@param array $attribs an associative array of html attributes
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L640-L646
|
schpill/thin
|
src/Navigation/Page.php
|
Page.removeCustomHtmlAttrib
|
public function removeCustomHtmlAttrib($name)
{
if (!is_string($name)) {
throw new Exception(
'Invalid argument: $name must be a string'
);
}
if (isset($this->_customHtmlAttribs[$name])) {
unset($this->_customHtmlAttribs[$name]);
}
}
|
php
|
public function removeCustomHtmlAttrib($name)
{
if (!is_string($name)) {
throw new Exception(
'Invalid argument: $name must be a string'
);
}
if (isset($this->_customHtmlAttribs[$name])) {
unset($this->_customHtmlAttribs[$name]);
}
}
|
Removes a custom HTML attribute from the page
@param string $name name of the custom HTML attribute
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L664-L675
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setOrder
|
public function setOrder($order = null)
{
if (is_string($order)) {
$temp = (int) $order;
if ($temp < 0 || $temp > 0 || $order == '0') {
$order = $temp;
}
}
if (null !== $order && !is_int($order)) {
throw new Exception(
'Invalid argument: $order must be an integer or null, ' .
'or a string that casts to an integer');
}
$this->_order = $order;
// notify parent, if any
if (isset($this->_parent)) {
$this->_parent->notifyOrderUpdated();
}
return $this;
}
|
php
|
public function setOrder($order = null)
{
if (is_string($order)) {
$temp = (int) $order;
if ($temp < 0 || $temp > 0 || $order == '0') {
$order = $temp;
}
}
if (null !== $order && !is_int($order)) {
throw new Exception(
'Invalid argument: $order must be an integer or null, ' .
'or a string that casts to an integer');
}
$this->_order = $order;
// notify parent, if any
if (isset($this->_parent)) {
$this->_parent->notifyOrderUpdated();
}
return $this;
}
|
Sets page order to use in parent container
@param int $order [optional] page order in container.
Default is null, which sets no
specific order.
@return Page fluent interface, returns self
@throws Exception if order is not integer or null
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L698-L721
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setResource
|
public function setResource($resource = null)
{
if (null === $resource || is_string($resource) ||
$resource instanceof Acl) {
$this->_resource = $resource;
} else {
require_once 'Zend/Navigation/Exception.php';
throw new Exception(
'Invalid argument: $resource must be null, a string, ' .
' or an instance of Acl');
}
return $this;
}
|
php
|
public function setResource($resource = null)
{
if (null === $resource || is_string($resource) ||
$resource instanceof Acl) {
$this->_resource = $resource;
} else {
require_once 'Zend/Navigation/Exception.php';
throw new Exception(
'Invalid argument: $resource must be null, a string, ' .
' or an instance of Acl');
}
return $this;
}
|
Sets ACL resource assoicated with this page
@param string|Acl $resource [optional] resource
to associate with
page. Default is
null, which sets no
resource.
@throws Exception if $resource if
invalid
@return Page fluent interface,
returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L746-L759
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setPrivilege
|
public function setPrivilege($privilege = null)
{
$this->_privilege = is_string($privilege) ? $privilege : null;
return $this;
}
|
php
|
public function setPrivilege($privilege = null)
{
$this->_privilege = is_string($privilege) ? $privilege : null;
return $this;
}
|
Sets ACL privilege associated with this page
@param string|null $privilege [optional] ACL privilege to associate
with this page. Default is null, which
sets no privilege.
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L779-L783
|
schpill/thin
|
src/Navigation/Page.php
|
Page.isActive
|
public function isActive($recursive = false)
{
if (!$this->_active && $recursive) {
foreach ($this->_pages as $page) {
if ($page->isActive(true)) {
return true;
}
}
return false;
}
return $this->_active;
}
|
php
|
public function isActive($recursive = false)
{
if (!$this->_active && $recursive) {
foreach ($this->_pages as $page) {
if ($page->isActive(true)) {
return true;
}
}
return false;
}
return $this->_active;
}
|
Returns whether page should be considered active or not
@param bool $recursive [optional] whether page should be considered
active if any child pages are active. Default is
false.
@return bool whether page should be considered active
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L816-L829
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setVisible
|
public function setVisible($visible = true)
{
if (is_string($visible) && 'false' == strtolower($visible)) {
$visible = false;
}
$this->_visible = (bool) $visible;
return $this;
}
|
php
|
public function setVisible($visible = true)
{
if (is_string($visible) && 'false' == strtolower($visible)) {
$visible = false;
}
$this->_visible = (bool) $visible;
return $this;
}
|
Sets whether the page should be visible or not
@param bool $visible [optional] whether page should be
considered visible or not. Default is true.
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L851-L858
|
schpill/thin
|
src/Navigation/Page.php
|
Page.isVisible
|
public function isVisible($recursive = false)
{
if ($recursive && isset($this->_parent) &&
$this->_parent instanceof Page) {
if (!$this->_parent->isVisible(true)) {
return false;
}
}
return $this->_visible;
}
|
php
|
public function isVisible($recursive = false)
{
if ($recursive && isset($this->_parent) &&
$this->_parent instanceof Page) {
if (!$this->_parent->isVisible(true)) {
return false;
}
}
return $this->_visible;
}
|
Returns a boolean value indicating whether the page is visible
@param bool $recursive [optional] whether page should be considered
invisible if parent is invisible. Default is
false.
@return bool whether page should be considered visible
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L868-L878
|
schpill/thin
|
src/Navigation/Page.php
|
Page.setParent
|
public function setParent(Container $parent = null)
{
if ($parent === $this) {
throw new Exception(
'A page cannot have itself as a parent');
}
// return if the given parent already is parent
if ($parent === $this->_parent) {
return $this;
}
// remove from old parent
if (null !== $this->_parent) {
$this->_parent->removePage($this);
}
// set new parent
$this->_parent = $parent;
// add to parent if page and not already a child
if (null !== $this->_parent && !$this->_parent->hasPage($this, false)) {
$this->_parent->addPage($this);
}
return $this;
}
|
php
|
public function setParent(Container $parent = null)
{
if ($parent === $this) {
throw new Exception(
'A page cannot have itself as a parent');
}
// return if the given parent already is parent
if ($parent === $this->_parent) {
return $this;
}
// remove from old parent
if (null !== $this->_parent) {
$this->_parent->removePage($this);
}
// set new parent
$this->_parent = $parent;
// add to parent if page and not already a child
if (null !== $this->_parent && !$this->_parent->hasPage($this, false)) {
$this->_parent->addPage($this);
}
return $this;
}
|
Sets parent container
@param Container $parent [optional] new parent to set.
Default is null which will set
no parent.
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L903-L929
|
schpill/thin
|
src/Navigation/Page.php
|
Page.set
|
public function set($property, $value)
{
if (!is_string($property) || empty($property)) {
throw new Exception(
'Invalid argument: $property must be a non-empty string');
}
$method = 'set' . self::_normalizePropertyName($property);
if ($method != 'setOptions' && $method != 'setConfig' &&
method_exists($this, $method)) {
$this->$method($value);
} else {
$this->_properties[$property] = $value;
}
return $this;
}
|
php
|
public function set($property, $value)
{
if (!is_string($property) || empty($property)) {
throw new Exception(
'Invalid argument: $property must be a non-empty string');
}
$method = 'set' . self::_normalizePropertyName($property);
if ($method != 'setOptions' && $method != 'setConfig' &&
method_exists($this, $method)) {
$this->$method($value);
} else {
$this->_properties[$property] = $value;
}
return $this;
}
|
Sets the given property
If the given property is native (id, class, title, etc), the matching
set method will be used. Otherwise, it will be set as a custom property.
@param string $property property name
@param mixed $value value to set
@return Page fluent interface, returns self
@throws Exception if property name is invalid
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L952-L969
|
schpill/thin
|
src/Navigation/Page.php
|
Page.get
|
public function get($property)
{
if (!is_string($property) || empty($property)) {
throw new Exception(
'Invalid argument: $property must be a non-empty string');
}
$method = 'get' . self::_normalizePropertyName($property);
if (method_exists($this, $method)) {
return $this->$method();
} elseif (isset($this->_properties[$property])) {
return $this->_properties[$property];
}
return null;
}
|
php
|
public function get($property)
{
if (!is_string($property) || empty($property)) {
throw new Exception(
'Invalid argument: $property must be a non-empty string');
}
$method = 'get' . self::_normalizePropertyName($property);
if (method_exists($this, $method)) {
return $this->$method();
} elseif (isset($this->_properties[$property])) {
return $this->_properties[$property];
}
return null;
}
|
Returns the value of the given property
If the given property is native (id, class, title, etc), the matching
get method will be used. Otherwise, it will return the matching custom
property, or null if not found.
@param string $property property name
@return mixed the property's value or null
@throws Exception if property name is invalid
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L982-L998
|
schpill/thin
|
src/Navigation/Page.php
|
Page.__isset
|
public function __isset($name)
{
$method = 'get' . self::_normalizePropertyName($name);
if (method_exists($this, $method)) {
return true;
}
return isset($this->_properties[$name]);
}
|
php
|
public function __isset($name)
{
$method = 'get' . self::_normalizePropertyName($name);
if (method_exists($this, $method)) {
return true;
}
return isset($this->_properties[$name]);
}
|
Checks if a property is set
Magic overload for enabling <code>isset($page->propname)</code>.
Returns true if the property is native (id, class, title, etc), and
true or false if it's a custom property (depending on whether the
property actually is set).
@param string $name property name
@return bool whether the given property exists
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L1043-L1051
|
schpill/thin
|
src/Navigation/Page.php
|
Page.addRel
|
public function addRel($relation, $value)
{
if (is_string($relation)) {
$this->_rel[$relation] = $value;
}
return $this;
}
|
php
|
public function addRel($relation, $value)
{
if (is_string($relation)) {
$this->_rel[$relation] = $value;
}
return $this;
}
|
Adds a forward relation to the page
@param string $relation relation name (e.g. alternate, glossary,
canonical, etc)
@param mixed $value value to set for relation
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L1098-L1105
|
schpill/thin
|
src/Navigation/Page.php
|
Page.addRev
|
public function addRev($relation, $value)
{
if (is_string($relation)) {
$this->_rev[$relation] = $value;
}
return $this;
}
|
php
|
public function addRev($relation, $value)
{
if (is_string($relation)) {
$this->_rev[$relation] = $value;
}
return $this;
}
|
Adds a reverse relation to the page
@param string $relation relation name (e.g. alternate, glossary,
canonical, etc)
@param mixed $value value to set for relation
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L1115-L1122
|
schpill/thin
|
src/Navigation/Page.php
|
Page.removeRel
|
public function removeRel($relation)
{
if (isset($this->_rel[$relation])) {
unset($this->_rel[$relation]);
}
return $this;
}
|
php
|
public function removeRel($relation)
{
if (isset($this->_rel[$relation])) {
unset($this->_rel[$relation]);
}
return $this;
}
|
Removes a forward relation from the page
@param string $relation name of relation to remove
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L1130-L1137
|
schpill/thin
|
src/Navigation/Page.php
|
Page.removeRev
|
public function removeRev($relation)
{
if (isset($this->_rev[$relation])) {
unset($this->_rev[$relation]);
}
return $this;
}
|
php
|
public function removeRev($relation)
{
if (isset($this->_rev[$relation])) {
unset($this->_rev[$relation]);
}
return $this;
}
|
Removes a reverse relation from the page
@param string $relation name of relation to remove
@return Page fluent interface, returns self
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L1145-L1152
|
schpill/thin
|
src/Navigation/Page.php
|
Page.toArray
|
public function toArray()
{
return array_merge(
$this->getCustomProperties(),
array(
'label' => $this->getlabel(),
'fragment' => $this->getFragment(),
'id' => $this->getId(),
'class' => $this->getClass(),
'title' => $this->getTitle(),
'target' => $this->getTarget(),
'accesskey' => $this->getAccesskey(),
'rel' => $this->getRel(),
'rev' => $this->getRev(),
'customHtmlAttribs' => $this->getCustomHtmlAttribs(),
'order' => $this->getOrder(),
'resource' => $this->getResource(),
'privilege' => $this->getPrivilege(),
'active' => $this->isActive(),
'visible' => $this->isVisible(),
'type' => get_class($this),
'pages' => parent::toArray()
)
);
}
|
php
|
public function toArray()
{
return array_merge(
$this->getCustomProperties(),
array(
'label' => $this->getlabel(),
'fragment' => $this->getFragment(),
'id' => $this->getId(),
'class' => $this->getClass(),
'title' => $this->getTitle(),
'target' => $this->getTarget(),
'accesskey' => $this->getAccesskey(),
'rel' => $this->getRel(),
'rev' => $this->getRev(),
'customHtmlAttribs' => $this->getCustomHtmlAttribs(),
'order' => $this->getOrder(),
'resource' => $this->getResource(),
'privilege' => $this->getPrivilege(),
'active' => $this->isActive(),
'visible' => $this->isVisible(),
'type' => get_class($this),
'pages' => parent::toArray()
)
);
}
|
Returns an array representation of the page
@return array associative array containing all page properties
|
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page.php#L1199-L1223
|
SpoonX/SxBootstrap
|
src/SxBootstrap/View/Helper/Bootstrap/AbstractElementHelper.php
|
AbstractElementHelper.translate
|
protected function translate($string)
{
if ($this->hasTranslator()) {
return $this->getTranslator()->translate($string, $this->getTranslatorTextDomain());
}
return $string;
}
|
php
|
protected function translate($string)
{
if ($this->hasTranslator()) {
return $this->getTranslator()->translate($string, $this->getTranslatorTextDomain());
}
return $string;
}
|
Translate a string.
@param $string
@return string
|
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/AbstractElementHelper.php#L42-L49
|
SpoonX/SxBootstrap
|
src/SxBootstrap/View/Helper/Bootstrap/AbstractElementHelper.php
|
AbstractElementHelper.addAttribute
|
public function addAttribute($key, $value = null)
{
$this->element->addAttribute($key, $value);
return $this;
}
|
php
|
public function addAttribute($key, $value = null)
{
$this->element->addAttribute($key, $value);
return $this;
}
|
Add attribute on element
@param string $key
@param string $value
@return $this
|
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/AbstractElementHelper.php#L59-L64
|
infusephp/auth
|
src/Libs/Storage/SessionStorage.php
|
SessionStorage.getUserSession
|
private function getUserSession(Request $req)
{
// check for a session hijacking attempt via the stored user agent
if ($req->session(self::SESSION_USER_AGENT_KEY) !== $req->agent()) {
return false;
}
$userId = $req->session(self::SESSION_USER_ID_KEY);
if ($userId === null) {
return false;
}
// if this is a guest user then just return it now
$userClass = $this->auth->getUserClass();
if ($userId <= 0) {
return new $userClass($userId);
}
// look up the registered user
$user = $userClass::where('id', $userId)->first();
if (!$user) {
return false;
}
// refresh the active session
if (session_status() == PHP_SESSION_ACTIVE) {
// check if the session valid
$sid = session_id();
if (!$this->sessionIsValid($sid)) {
return false;
}
$this->refreshSession($sid);
}
// check if the user is 2FA verified
if ($req->session(self::SESSION_2FA_VERIFIED_KEY)) {
$user->markTwoFactorVerified();
}
return $user->markSignedIn();
}
|
php
|
private function getUserSession(Request $req)
{
// check for a session hijacking attempt via the stored user agent
if ($req->session(self::SESSION_USER_AGENT_KEY) !== $req->agent()) {
return false;
}
$userId = $req->session(self::SESSION_USER_ID_KEY);
if ($userId === null) {
return false;
}
// if this is a guest user then just return it now
$userClass = $this->auth->getUserClass();
if ($userId <= 0) {
return new $userClass($userId);
}
// look up the registered user
$user = $userClass::where('id', $userId)->first();
if (!$user) {
return false;
}
// refresh the active session
if (session_status() == PHP_SESSION_ACTIVE) {
// check if the session valid
$sid = session_id();
if (!$this->sessionIsValid($sid)) {
return false;
}
$this->refreshSession($sid);
}
// check if the user is 2FA verified
if ($req->session(self::SESSION_2FA_VERIFIED_KEY)) {
$user->markTwoFactorVerified();
}
return $user->markSignedIn();
}
|
Tries to get an authenticated user via the current session.
@param Request $req
@return UserInterface|false
|
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SessionStorage.php#L164-L205
|
temp/media-converter
|
src/Extractor/RawAudioExtractor.php
|
RawAudioExtractor.supports
|
public function supports($filename, MediaType $mediaType, Specification $targetFormat)
{
return $targetFormat instanceof Audio && $mediaType->getCategory() === 'audio';
}
|
php
|
public function supports($filename, MediaType $mediaType, Specification $targetFormat)
{
return $targetFormat instanceof Audio && $mediaType->getCategory() === 'audio';
}
|
{@inheritdoc}
|
https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Extractor/RawAudioExtractor.php#L26-L29
|
symfony2admingenerator/FormBundle
|
DependencyInjection/Compiler/FormCompilerPass.php
|
FormCompilerPass.process
|
public function process(ContainerBuilder $container)
{
// Used templates
$templates = ['@AdmingeneratorForm/form_js.html.twig', '@AdmingeneratorForm/form_css.html.twig'];
$resources = $container->getParameter('twig.form.resources');
$alreadyImported = count(array_intersect($resources, $templates)) == count($templates);
if (!$alreadyImported) {
// Insert right after form_div_layout.html.twig if exists
if (($key = array_search('form_div_layout.html.twig', $resources)) !== false) {
array_splice($resources, ++$key, 0, $templates);
} else {
// Put it in first position
array_unshift($resources, $templates);
}
$container->setParameter('twig.form.resources', $resources);
}
}
|
php
|
public function process(ContainerBuilder $container)
{
// Used templates
$templates = ['@AdmingeneratorForm/form_js.html.twig', '@AdmingeneratorForm/form_css.html.twig'];
$resources = $container->getParameter('twig.form.resources');
$alreadyImported = count(array_intersect($resources, $templates)) == count($templates);
if (!$alreadyImported) {
// Insert right after form_div_layout.html.twig if exists
if (($key = array_search('form_div_layout.html.twig', $resources)) !== false) {
array_splice($resources, ++$key, 0, $templates);
} else {
// Put it in first position
array_unshift($resources, $templates);
}
$container->setParameter('twig.form.resources', $resources);
}
}
|
{@inheritdoc}
|
https://github.com/symfony2admingenerator/FormBundle/blob/0f0dbf8f0aecc3332daa959771af611f00b35359/DependencyInjection/Compiler/FormCompilerPass.php#L19-L38
|
inhere/php-library-plus
|
libs/Task/Worker/Manager.php
|
Manager.run
|
public function run()
{
$this->beforeRun();
$this->isMaster = true;
$this->stopWork = false;
$this->stat['startTime'] = time();
$this->setProcessTitle(sprintf('php-twm: master process%s (%s)', $this->getShowName(), getcwd() . '/' . $this->fullScript));
$this->prepare();
$this->beforeStart();
$this->workers = $this->startWorkers($this->config['workerNum']);
$this->startManager();
$this->afterRun();
}
|
php
|
public function run()
{
$this->beforeRun();
$this->isMaster = true;
$this->stopWork = false;
$this->stat['startTime'] = time();
$this->setProcessTitle(sprintf('php-twm: master process%s (%s)', $this->getShowName(), getcwd() . '/' . $this->fullScript));
$this->prepare();
$this->beforeStart();
$this->workers = $this->startWorkers($this->config['workerNum']);
$this->startManager();
$this->afterRun();
}
|
run
|
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Worker/Manager.php#L150-L169
|
inhere/php-library-plus
|
libs/Task/Worker/Manager.php
|
Manager.showHelp
|
protected function showHelp($msg = '', $code = 0)
{
$usage = Cli::color('USAGE:', 'brown');
$commands = Cli::color('COMMANDS:', 'brown');
$sOptions = Cli::color('SPECIAL OPTIONS:', 'brown');
$pOptions = Cli::color('PUBLIC OPTIONS:', 'brown');
$version = Cli::color(self::VERSION, 'green');
$script = $this->getScript();
if ($msg) {
$code = $code ?: self::CODE_UNKNOWN_ERROR;
echo Cli::color('ERROR:', 'light_red') . "\n " . wordwrap($msg, 108, "\n ") . "\n\n";
}
echo <<<EOF
Gearman worker manager(gwm) script tool. Version $version(lite)
$usage
$script {COMMAND} -c CONFIG [-v LEVEL] [-l LOG_FILE] [-d] [-w] [-p PID_FILE]
$script -h
$script -D
$commands
start Start gearman worker manager(default)
stop Stop running's gearman worker manager
restart Restart running's gearman worker manager
reload Reload all running workers of the manager
status Get gearman worker manager runtime status
$sOptions
start/restart
-d,--daemon Daemon, detach and run in the background
--tasks Only register the assigned tasks, multi task name separated by commas(',')
--no-test Not add test handler, when task name prefix is 'test'.(eg: test_task)
status
--cmd COMMAND Send command when connect to the task server. allow:status,workers.(default:status)
--watch-status Watch status command, will auto refresh status.
$pOptions
-c CONFIG Load a custom worker manager configuration file
-s HOST[:PORT] Connect to server HOST and optional PORT, multi server separated by commas(',')
-n NUMBER Start NUMBER workers that do all tasks
-l LOG_FILE Log output to LOG_FILE or use keyword 'syslog' for syslog support
-p PID_FILE File to write master process ID out to
-r NUMBER Maximum run task iterations per worker
-x SECONDS Maximum seconds for a worker to live
-t SECONDS Number of seconds gearmand server should wait for a worker to complete work before timing out
-v [LEVEL] Increase verbosity level by one. eg: -v vv | -v vvv
-h,--help Shows this help information
-V,--version Display the version of the manager
-D,--dump [all] Parse the command line and config file then dump it to the screen and exit.\n\n
EOF;
$this->quit($code);
}
|
php
|
protected function showHelp($msg = '', $code = 0)
{
$usage = Cli::color('USAGE:', 'brown');
$commands = Cli::color('COMMANDS:', 'brown');
$sOptions = Cli::color('SPECIAL OPTIONS:', 'brown');
$pOptions = Cli::color('PUBLIC OPTIONS:', 'brown');
$version = Cli::color(self::VERSION, 'green');
$script = $this->getScript();
if ($msg) {
$code = $code ?: self::CODE_UNKNOWN_ERROR;
echo Cli::color('ERROR:', 'light_red') . "\n " . wordwrap($msg, 108, "\n ") . "\n\n";
}
echo <<<EOF
Gearman worker manager(gwm) script tool. Version $version(lite)
$usage
$script {COMMAND} -c CONFIG [-v LEVEL] [-l LOG_FILE] [-d] [-w] [-p PID_FILE]
$script -h
$script -D
$commands
start Start gearman worker manager(default)
stop Stop running's gearman worker manager
restart Restart running's gearman worker manager
reload Reload all running workers of the manager
status Get gearman worker manager runtime status
$sOptions
start/restart
-d,--daemon Daemon, detach and run in the background
--tasks Only register the assigned tasks, multi task name separated by commas(',')
--no-test Not add test handler, when task name prefix is 'test'.(eg: test_task)
status
--cmd COMMAND Send command when connect to the task server. allow:status,workers.(default:status)
--watch-status Watch status command, will auto refresh status.
$pOptions
-c CONFIG Load a custom worker manager configuration file
-s HOST[:PORT] Connect to server HOST and optional PORT, multi server separated by commas(',')
-n NUMBER Start NUMBER workers that do all tasks
-l LOG_FILE Log output to LOG_FILE or use keyword 'syslog' for syslog support
-p PID_FILE File to write master process ID out to
-r NUMBER Maximum run task iterations per worker
-x SECONDS Maximum seconds for a worker to live
-t SECONDS Number of seconds gearmand server should wait for a worker to complete work before timing out
-v [LEVEL] Increase verbosity level by one. eg: -v vv | -v vvv
-h,--help Shows this help information
-V,--version Display the version of the manager
-D,--dump [all] Parse the command line and config file then dump it to the screen and exit.\n\n
EOF;
$this->quit($code);
}
|
Shows the scripts help info with optional error message
@param string $msg
@param int $code The exit code
|
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Worker/Manager.php#L249-L308
|
inhere/php-library-plus
|
libs/Task/Worker/Manager.php
|
Manager.dumpInfo
|
public function dumpInfo($allInfo = false)
{
if ($allInfo) {
$this->stdout("There are all information of the manager:\n" . PhpHelper::printVar($this));
} else {
$this->stdout("There are configure information:\n" . PhpHelper::printVar($this->config));
}
$this->quit();
}
|
php
|
public function dumpInfo($allInfo = false)
{
if ($allInfo) {
$this->stdout("There are all information of the manager:\n" . PhpHelper::printVar($this));
} else {
$this->stdout("There are configure information:\n" . PhpHelper::printVar($this->config));
}
$this->quit();
}
|
dumpInfo
@param bool $allInfo
|
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Worker/Manager.php#L324-L333
|
inhere/php-library-plus
|
libs/Task/Worker/Manager.php
|
Manager.installSignals
|
public function installSignals($isMaster = true)
{
// ignore
pcntl_signal(SIGPIPE, SIG_IGN, false);
if ($isMaster) {
$this->log('Registering signal handlers for master(parent) process', ProcessLogger::DEBUG);
pcntl_signal(SIGTERM, [$this, 'signalHandler'], false);
pcntl_signal(SIGINT, [$this, 'signalHandler'], false);
pcntl_signal(SIGUSR1, [$this, 'signalHandler'], false);
pcntl_signal(SIGUSR2, [$this, 'signalHandler'], false);
pcntl_signal(SIGHUP, [$this, 'signalHandler'], false);
pcntl_signal(SIGCHLD, [$this, 'signalHandler'], false);
} else {
$this->log('Registering signal handlers for current worker process', ProcessLogger::DEBUG);
pcntl_signal(SIGTERM, [$this, 'signalHandler'], false);
}
}
|
php
|
public function installSignals($isMaster = true)
{
// ignore
pcntl_signal(SIGPIPE, SIG_IGN, false);
if ($isMaster) {
$this->log('Registering signal handlers for master(parent) process', ProcessLogger::DEBUG);
pcntl_signal(SIGTERM, [$this, 'signalHandler'], false);
pcntl_signal(SIGINT, [$this, 'signalHandler'], false);
pcntl_signal(SIGUSR1, [$this, 'signalHandler'], false);
pcntl_signal(SIGUSR2, [$this, 'signalHandler'], false);
pcntl_signal(SIGHUP, [$this, 'signalHandler'], false);
pcntl_signal(SIGCHLD, [$this, 'signalHandler'], false);
} else {
$this->log('Registering signal handlers for current worker process', ProcessLogger::DEBUG);
pcntl_signal(SIGTERM, [$this, 'signalHandler'], false);
}
}
|
{@inheritDoc}
|
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Worker/Manager.php#L338-L360
|
inhere/php-library-plus
|
libs/Task/Worker/Manager.php
|
Manager.signalHandler
|
public function signalHandler($sigNo)
{
if ($this->isMaster) {
static $stopCount = 0;
switch ($sigNo) {
case SIGINT: // Ctrl + C
case SIGTERM:
$sigText = $sigNo === SIGINT ? 'SIGINT' : 'SIGTERM';
$this->log("Shutting down(signal:$sigText)...", ProcessLogger::PROC_INFO);
$this->stopWork();
$stopCount++;
if ($stopCount < 5) {
$this->stopWorkers();
} else {
$this->log('Stop workers failed by(signal:SIGTERM), force kill workers by(signal:SIGKILL)', ProcessLogger::PROC_INFO);
$this->stopWorkers(SIGKILL);
}
break;
case SIGHUP:
$this->log('Restarting workers(signal:SIGHUP)', ProcessLogger::PROC_INFO);
$this->stopWorkers();
break;
case SIGUSR1: // reload workers and reload handlers
// $this->log('Reloading workers and handlers(signal:SIGUSR1)', ProcessLogger::PROC_INFO);
// $this->stopWork();
// $this->start();
break;
case SIGUSR2:
break;
default:
// handle all other signals
}
} else {
$this->stopWork();
$this->log("Received 'stopWork' signal(signal:SIGTERM), will be exiting.", ProcessLogger::PROC_INFO);
}
}
|
php
|
public function signalHandler($sigNo)
{
if ($this->isMaster) {
static $stopCount = 0;
switch ($sigNo) {
case SIGINT: // Ctrl + C
case SIGTERM:
$sigText = $sigNo === SIGINT ? 'SIGINT' : 'SIGTERM';
$this->log("Shutting down(signal:$sigText)...", ProcessLogger::PROC_INFO);
$this->stopWork();
$stopCount++;
if ($stopCount < 5) {
$this->stopWorkers();
} else {
$this->log('Stop workers failed by(signal:SIGTERM), force kill workers by(signal:SIGKILL)', ProcessLogger::PROC_INFO);
$this->stopWorkers(SIGKILL);
}
break;
case SIGHUP:
$this->log('Restarting workers(signal:SIGHUP)', ProcessLogger::PROC_INFO);
$this->stopWorkers();
break;
case SIGUSR1: // reload workers and reload handlers
// $this->log('Reloading workers and handlers(signal:SIGUSR1)', ProcessLogger::PROC_INFO);
// $this->stopWork();
// $this->start();
break;
case SIGUSR2:
break;
default:
// handle all other signals
}
} else {
$this->stopWork();
$this->log("Received 'stopWork' signal(signal:SIGTERM), will be exiting.", ProcessLogger::PROC_INFO);
}
}
|
Handles signals
@param int $sigNo
|
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Worker/Manager.php#L366-L405
|
groundctrl/discourse-sso-php
|
src/QueryString.php
|
QueryString.isValid
|
public function isValid($key)
{
if (! isset ($this['sso'], $this['sig'])) {
return false;
}
return $this['sig'] === Secret::create($key)->sign($this['sso']);
}
|
php
|
public function isValid($key)
{
if (! isset ($this['sso'], $this['sig'])) {
return false;
}
return $this['sig'] === Secret::create($key)->sign($this['sso']);
}
|
Checks the validity of this QueryString's against a secret key.
@param string|Secret $key
@return bool
|
https://github.com/groundctrl/discourse-sso-php/blob/8ef1d0ced2e0502b673b25c46aab09cce2efc765/src/QueryString.php#L11-L18
|
groundctrl/discourse-sso-php
|
src/QueryString.php
|
QueryString.fromString
|
public static function fromString($query, array $data = [])
{
$url = parse_url($query);
$query = isset($url['query']) ? $url['query'] : $url['path'];
parse_str($query, $data);
return new QueryString($data);
}
|
php
|
public static function fromString($query, array $data = [])
{
$url = parse_url($query);
$query = isset($url['query']) ? $url['query'] : $url['path'];
parse_str($query, $data);
return new QueryString($data);
}
|
Creates a QueryString from a string.
@param string $query A url or query string part.
@param array $data An optional data array.
@return QueryString
|
https://github.com/groundctrl/discourse-sso-php/blob/8ef1d0ced2e0502b673b25c46aab09cce2efc765/src/QueryString.php#L38-L45
|
groundctrl/discourse-sso-php
|
src/QueryString.php
|
QueryString.normalize
|
static public function normalize(array $params)
{
$qs = http_build_query($params, null, '&');
if ('' == $qs) {
return '';
}
$parts = array();
$order = array();
foreach (explode('&', $qs) as $param) {
if ('' === $param || '=' === $param[0]) {
// Ignore useless delimiters, e.g. "x=y&".
// Also ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway.
// PHP also does not include them when building _GET.
continue;
}
$keyValuePair = explode('=', $param, 2);
// GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded).
// PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str. This is why we use urldecode and then normalize to
// RFC 3986 with rawurlencode.
$parts[] = isset($keyValuePair[1]) ?
rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) :
rawurlencode(urldecode($keyValuePair[0]));
$order[] = urldecode($keyValuePair[0]);
}
array_multisort($order, SORT_ASC, $parts);
return implode('&', $parts);
}
|
php
|
static public function normalize(array $params)
{
$qs = http_build_query($params, null, '&');
if ('' == $qs) {
return '';
}
$parts = array();
$order = array();
foreach (explode('&', $qs) as $param) {
if ('' === $param || '=' === $param[0]) {
// Ignore useless delimiters, e.g. "x=y&".
// Also ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway.
// PHP also does not include them when building _GET.
continue;
}
$keyValuePair = explode('=', $param, 2);
// GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded).
// PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str. This is why we use urldecode and then normalize to
// RFC 3986 with rawurlencode.
$parts[] = isset($keyValuePair[1]) ?
rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) :
rawurlencode(urldecode($keyValuePair[0]));
$order[] = urldecode($keyValuePair[0]);
}
array_multisort($order, SORT_ASC, $parts);
return implode('&', $parts);
}
|
Builds a normalized query string from the given parameters.
This normalization logic comes direct from Symfony's HttpFoundation Component.
Since this is the extent of the dependency, let's opt for a bit of code duplication instead.
@param array $params
@return string
|
https://github.com/groundctrl/discourse-sso-php/blob/8ef1d0ced2e0502b673b25c46aab09cce2efc765/src/QueryString.php#L56-L89
|
prooph/processing
|
library/Type/AbstractDictionary.php
|
AbstractDictionary.prototype
|
public static function prototype()
{
$implementer = get_called_class();
if (PrototypeRegistry::hasPrototype($implementer)) return PrototypeRegistry::getPrototype($implementer);
$propertyPrototypes = static::getPropertyPrototypes();
$propertyMap = array();
foreach ($propertyPrototypes as $propertyName => $propertyPrototype) {
$propertyMap[$propertyName] = new PrototypeProperty($propertyName, $propertyPrototype);
}
return new Prototype(
$implementer,
static::buildDescription(),
$propertyMap
);
}
|
php
|
public static function prototype()
{
$implementer = get_called_class();
if (PrototypeRegistry::hasPrototype($implementer)) return PrototypeRegistry::getPrototype($implementer);
$propertyPrototypes = static::getPropertyPrototypes();
$propertyMap = array();
foreach ($propertyPrototypes as $propertyName => $propertyPrototype) {
$propertyMap[$propertyName] = new PrototypeProperty($propertyName, $propertyPrototype);
}
return new Prototype(
$implementer,
static::buildDescription(),
$propertyMap
);
}
|
Provides access to a prototype of the Prooph\ProcessingType\Type (empty Object, with a Description and PrototypeProperties)
@return Prototype
|
https://github.com/prooph/processing/blob/a2947bccbffeecc4ca93a15e38ab53814e3e53e5/library/Type/AbstractDictionary.php#L41-L60
|
phOnion/framework
|
src/Dependency/CacheAwareContainer.php
|
CacheAwareContainer.resolveContainer
|
private function resolveContainer(): ContainerInterface
{
if ($this->container === null) {
$container = $this->containerFactory->build($this);
if (!$container instanceof ContainerInterface) {
throw new \RuntimeException(
"Invalid factory result, expected ContainerInterface"
);
}
$this->container = $container;
}
return $this->container;
}
|
php
|
private function resolveContainer(): ContainerInterface
{
if ($this->container === null) {
$container = $this->containerFactory->build($this);
if (!$container instanceof ContainerInterface) {
throw new \RuntimeException(
"Invalid factory result, expected ContainerInterface"
);
}
$this->container = $container;
}
return $this->container;
}
|
Instantiate the container if not and return it
@return ContainerInterface
|
https://github.com/phOnion/framework/blob/eb2d99cc65d3b39faecbfd49b602fb2c62349d05/src/Dependency/CacheAwareContainer.php#L76-L91
|
juliangut/doctrine-manager-builder
|
src/CouchDB/Repository/DefaultRepositoryFactory.php
|
DefaultRepositoryFactory.getRepository
|
public function getRepository(DocumentManager $documentManager, $documentName)
{
$repositoryHash =
$documentManager->getClassMetadata($documentName)->getName() . spl_object_hash($documentManager);
if (array_key_exists($repositoryHash, $this->repositoryList)) {
return $this->repositoryList[$repositoryHash];
}
$this->repositoryList[$repositoryHash] = $this->createRepository($documentManager, $documentName);
return $this->repositoryList[$repositoryHash];
}
|
php
|
public function getRepository(DocumentManager $documentManager, $documentName)
{
$repositoryHash =
$documentManager->getClassMetadata($documentName)->getName() . spl_object_hash($documentManager);
if (array_key_exists($repositoryHash, $this->repositoryList)) {
return $this->repositoryList[$repositoryHash];
}
$this->repositoryList[$repositoryHash] = $this->createRepository($documentManager, $documentName);
return $this->repositoryList[$repositoryHash];
}
|
{@inheritdoc}
|
https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/CouchDB/Repository/DefaultRepositoryFactory.php#L31-L43
|
juliangut/doctrine-manager-builder
|
src/CouchDB/Repository/DefaultRepositoryFactory.php
|
DefaultRepositoryFactory.createRepository
|
private function createRepository(DocumentManager $documentManager, $documentName)
{
/* @var $metadata \Doctrine\ODM\CouchDB\Mapping\ClassMetadata */
$metadata = $documentManager->getClassMetadata($documentName);
$repositoryClassName = $metadata->customRepositoryClassName
?: $documentManager->getDefaultRepositoryClassName();
return new $repositoryClassName($documentManager, $metadata);
}
|
php
|
private function createRepository(DocumentManager $documentManager, $documentName)
{
/* @var $metadata \Doctrine\ODM\CouchDB\Mapping\ClassMetadata */
$metadata = $documentManager->getClassMetadata($documentName);
$repositoryClassName = $metadata->customRepositoryClassName
?: $documentManager->getDefaultRepositoryClassName();
return new $repositoryClassName($documentManager, $metadata);
}
|
Create a new repository instance for a document class.
@param DocumentManager $documentManager
@param string $documentName
@return \Doctrine\Common\Persistence\ObjectRepository
|
https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/CouchDB/Repository/DefaultRepositoryFactory.php#L53-L61
|
Synapse-Cmf/synapse-cmf
|
src/Synapse/Admin/Bundle/Controller/TemplateAdminController.php
|
TemplateAdminController.listAction
|
public function listAction(Request $request)
{
$theme = $request->attributes->get(
'synapse_theme',
$this->container->get('synapse')
->enableDefaultTheme()
->getCurrentTheme()
);
$templateCollection = $this->container->get('synapse.template.loader')
->retrieveAll(array(
'scope' => TemplateInterface::GLOBAL_SCOPE,
'templateTypeId' => $theme->getTemplateTypes()->column('id')
))
;
$templateMap = array();
foreach ($templateCollection as $template) {
$templateMap[$template->getTemplateType()->getName()][$template->getContentType()->getName()] = $template;
}
return $this->render('SynapseAdminBundle:Template:list.html.twig', array(
'theme' => $theme,
'content_types' => $this->container->get('synapse.content_type.loader')
->retrieveAll(),
'templates' => $templateMap,
));
}
|
php
|
public function listAction(Request $request)
{
$theme = $request->attributes->get(
'synapse_theme',
$this->container->get('synapse')
->enableDefaultTheme()
->getCurrentTheme()
);
$templateCollection = $this->container->get('synapse.template.loader')
->retrieveAll(array(
'scope' => TemplateInterface::GLOBAL_SCOPE,
'templateTypeId' => $theme->getTemplateTypes()->column('id')
))
;
$templateMap = array();
foreach ($templateCollection as $template) {
$templateMap[$template->getTemplateType()->getName()][$template->getContentType()->getName()] = $template;
}
return $this->render('SynapseAdminBundle:Template:list.html.twig', array(
'theme' => $theme,
'content_types' => $this->container->get('synapse.content_type.loader')
->retrieveAll(),
'templates' => $templateMap,
));
}
|
Templates listing action.
@param Request $request
@return Response
|
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Admin/Bundle/Controller/TemplateAdminController.php#L25-L51
|
Synapse-Cmf/synapse-cmf
|
src/Synapse/Admin/Bundle/Controller/TemplateAdminController.php
|
TemplateAdminController.initAction
|
public function initAction(Request $request, $templateType, $contentType, $contentId = null)
{
$templateDomain = $this->container->get('synapse.template.domain');
$template = empty($contentId)
? $templateDomain->createGlobal(
$contentType,
$templateType
)
: $templateDomain->createLocal(
$this->container->get('synapse.content.resolver')->resolveContentId($contentType, $contentId),
$templateType
)
;
return new RedirectResponse(empty($contentId)
? $this->container->get('router')->generate('synapse_admin_template_edition', array(
'id' => $template->getId(),
))
: $request->server->get('HTTP_REFERER')
);
}
|
php
|
public function initAction(Request $request, $templateType, $contentType, $contentId = null)
{
$templateDomain = $this->container->get('synapse.template.domain');
$template = empty($contentId)
? $templateDomain->createGlobal(
$contentType,
$templateType
)
: $templateDomain->createLocal(
$this->container->get('synapse.content.resolver')->resolveContentId($contentType, $contentId),
$templateType
)
;
return new RedirectResponse(empty($contentId)
? $this->container->get('router')->generate('synapse_admin_template_edition', array(
'id' => $template->getId(),
))
: $request->server->get('HTTP_REFERER')
);
}
|
Template init action.
@param Request $request
@param string $templateType
@param string $contentType
@param int $contentId
@return Response
|
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Admin/Bundle/Controller/TemplateAdminController.php#L63-L84
|
Synapse-Cmf/synapse-cmf
|
src/Synapse/Admin/Bundle/Controller/TemplateAdminController.php
|
TemplateAdminController.editAction
|
public function editAction($id, Request $request)
{
$template = $this->container->get('synapse.template.orm_loader')
->retrieveOne(array(
'id' => $id,
'scope' => TemplateInterface::GLOBAL_SCOPE
))
;
if (!$template) {
throw new NotFoundHttpException(sprintf('No global template found for id "%s"', $id));
}
$form = $this->container->get('form.factory')->createNamed(
'template',
TemplateType::class,
$template,
array(
'theme' => $request->attributes->get(
'synapse_theme',
$this->container->get('synapse')
->enableDefaultTheme()
->getCurrentTheme()
),
'content_type' => $template->getContentType(),
'template_type' => $template->getTemplateType(),
'action' => $formUrl = $this->container->get('router')->generate(
'synapse_admin_template_edition',
array('id' => $template->getId())
),
'method' => 'POST',
'csrf_protection' => false,
)
);
if ($request->request->has('template')) {
$form->handleRequest($request);
if ($form->isValid()) {
return $this->redirect(
$this->container->get('router')->generate(
'synapse_admin_template_edition',
array('id' => $template->getId())
)
);
}
}
return $this->render('SynapseAdminBundle:Template:edit.html.twig', array(
'template' => $template,
'form' => $form->createView(),
));
}
|
php
|
public function editAction($id, Request $request)
{
$template = $this->container->get('synapse.template.orm_loader')
->retrieveOne(array(
'id' => $id,
'scope' => TemplateInterface::GLOBAL_SCOPE
))
;
if (!$template) {
throw new NotFoundHttpException(sprintf('No global template found for id "%s"', $id));
}
$form = $this->container->get('form.factory')->createNamed(
'template',
TemplateType::class,
$template,
array(
'theme' => $request->attributes->get(
'synapse_theme',
$this->container->get('synapse')
->enableDefaultTheme()
->getCurrentTheme()
),
'content_type' => $template->getContentType(),
'template_type' => $template->getTemplateType(),
'action' => $formUrl = $this->container->get('router')->generate(
'synapse_admin_template_edition',
array('id' => $template->getId())
),
'method' => 'POST',
'csrf_protection' => false,
)
);
if ($request->request->has('template')) {
$form->handleRequest($request);
if ($form->isValid()) {
return $this->redirect(
$this->container->get('router')->generate(
'synapse_admin_template_edition',
array('id' => $template->getId())
)
);
}
}
return $this->render('SynapseAdminBundle:Template:edit.html.twig', array(
'template' => $template,
'form' => $form->createView(),
));
}
|
Global template edition action.
Requires an activated or activable theme.
@param Request $request
@return Response
|
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Admin/Bundle/Controller/TemplateAdminController.php#L94-L143
|
Synapse-Cmf/synapse-cmf
|
src/Synapse/Admin/Bundle/Controller/TemplateAdminController.php
|
TemplateAdminController.addComponentAction
|
public function addComponentAction($id, $zoneTypeId, $componentTypeId, Request $request)
{
if (!$template = $this->container->get('synapse.template.loader')->retrieve($id)) {
throw new NotFoundHttpException(sprintf('No template found under id "%s"', $id));
}
if (!$zoneType = $template->getTemplateType()
->getZoneTypes()
->search(array('id' => $zoneTypeId))
->first()
) {
throw new NotFoundHttpException(sprintf(
'Zone type "%s" is not activated for template "%s". Please check theme configuration.',
$zoneTypeId,
$templateType->getId()
));
}
if (!$componentType = $this->container->get('synapse.component_type.loader')->retrieve($componentTypeId)) {
throw new NotFoundHttpException(sprintf(
'No defined component type found under id "%s". Please check theme configuration.',
$componentTypeId
));
}
$this->container->get('synapse.zone.domain')->addComponent(
$template->getZones()->search(array('zoneType' => $zoneType))->first(),
$componentType
);
return new RedirectResponse(
$request->server->get('HTTP_REFERER')
);
}
|
php
|
public function addComponentAction($id, $zoneTypeId, $componentTypeId, Request $request)
{
if (!$template = $this->container->get('synapse.template.loader')->retrieve($id)) {
throw new NotFoundHttpException(sprintf('No template found under id "%s"', $id));
}
if (!$zoneType = $template->getTemplateType()
->getZoneTypes()
->search(array('id' => $zoneTypeId))
->first()
) {
throw new NotFoundHttpException(sprintf(
'Zone type "%s" is not activated for template "%s". Please check theme configuration.',
$zoneTypeId,
$templateType->getId()
));
}
if (!$componentType = $this->container->get('synapse.component_type.loader')->retrieve($componentTypeId)) {
throw new NotFoundHttpException(sprintf(
'No defined component type found under id "%s". Please check theme configuration.',
$componentTypeId
));
}
$this->container->get('synapse.zone.domain')->addComponent(
$template->getZones()->search(array('zoneType' => $zoneType))->first(),
$componentType
);
return new RedirectResponse(
$request->server->get('HTTP_REFERER')
);
}
|
Adds a component of given type id into given template id and zone type id.
@param int $id
@param string $zoneTypeId
@param string $componentTypeId
@param Request $request
@return Response
|
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Admin/Bundle/Controller/TemplateAdminController.php#L155-L186
|
hal-platform/hal-core
|
src/Repository/EnvironmentRepository.php
|
EnvironmentRepository.getBuildableEnvironmentsByApplication
|
public function getBuildableEnvironmentsByApplication(Application $application)
{
$region = sprintf(self::ENV_QUERY_REGION, $application->id());
$dql = sprintf(self::DQL_BY_APPLICATION, Target::class, Environment::class);
$query = $this->getEntityManager()
->createQuery($dql)
->setCacheable(true)
->setCacheRegion($region)
->setParameter('application', $application);
$environments = $query->getResult();
usort($environments, $this->environmentSorter());
return $environments;
}
|
php
|
public function getBuildableEnvironmentsByApplication(Application $application)
{
$region = sprintf(self::ENV_QUERY_REGION, $application->id());
$dql = sprintf(self::DQL_BY_APPLICATION, Target::class, Environment::class);
$query = $this->getEntityManager()
->createQuery($dql)
->setCacheable(true)
->setCacheRegion($region)
->setParameter('application', $application);
$environments = $query->getResult();
usort($environments, $this->environmentSorter());
return $environments;
}
|
Get all buildable environments for an application.
@param Application $application
@return Environment[]
|
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Repository/EnvironmentRepository.php#L38-L55
|
hal-platform/hal-core
|
src/Repository/EnvironmentRepository.php
|
EnvironmentRepository.clearBuildableEnvironmentsByApplication
|
public function clearBuildableEnvironmentsByApplication(Application $application)
{
$region = sprintf(self::ENV_QUERY_REGION, $application->id());
$cache = $this
->getEntityManager()
->getCache();
$cache
->getQueryCache($region)
->clear();
}
|
php
|
public function clearBuildableEnvironmentsByApplication(Application $application)
{
$region = sprintf(self::ENV_QUERY_REGION, $application->id());
$cache = $this
->getEntityManager()
->getCache();
$cache
->getQueryCache($region)
->clear();
}
|
Clear cache for buildable environments for an application.
@param Application $application
@return void
|
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Repository/EnvironmentRepository.php#L64-L75
|
hal-platform/hal-core
|
src/Repository/EnvironmentRepository.php
|
EnvironmentRepository.getAllEnvironmentsSorted
|
public function getAllEnvironmentsSorted(?callable $sorter = null)
{
$environments = $this->findAll();
if ($sorter) {
usort($environments, $sorter);
} else {
usort($environments, $this->environmentSorter());
}
return $environments;
}
|
php
|
public function getAllEnvironmentsSorted(?callable $sorter = null)
{
$environments = $this->findAll();
if ($sorter) {
usort($environments, $sorter);
} else {
usort($environments, $this->environmentSorter());
}
return $environments;
}
|
@param callable|null $sorter
@return Environment[]
|
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Repository/EnvironmentRepository.php#L82-L93
|
CodeCollab/Http
|
src/Response/Response.php
|
Response.setStatusCode
|
public function setStatusCode(int $numeric, string $textual = null)
{
$this->numericStatusCode = $numeric;
if ($textual !== null) {
$this->textualStatusCode = $textual;
}
}
|
php
|
public function setStatusCode(int $numeric, string $textual = null)
{
$this->numericStatusCode = $numeric;
if ($textual !== null) {
$this->textualStatusCode = $textual;
}
}
|
Sets the status code
@param int $numeric Numerical status code representation
@param string $textual Textual status code representation
|
https://github.com/CodeCollab/Http/blob/b1f8306b20daebcf26ed4b13c032c5bc008a0861/src/Response/Response.php#L100-L107
|
CodeCollab/Http
|
src/Response/Response.php
|
Response.addCookie
|
public function addCookie(string $key, $value, \DateTimeInterface $expire)
{
$this->cookies[$key] = $this->cookieFactory->build($key, $value, $expire);
}
|
php
|
public function addCookie(string $key, $value, \DateTimeInterface $expire)
{
$this->cookies[$key] = $this->cookieFactory->build($key, $value, $expire);
}
|
Adds a cookie
@param string $key The name of the cookie
@param mixed $value The value pf the cookie
@param \DateTimeInterface $expire The expiration date
|
https://github.com/CodeCollab/Http/blob/b1f8306b20daebcf26ed4b13c032c5bc008a0861/src/Response/Response.php#L127-L130
|
CodeCollab/Http
|
src/Response/Response.php
|
Response.send
|
public function send()
{
$this->sendCookies();
$this->sendHeaders();
if ($this->request->server('REQUEST_METHOD') === 'HEAD') {
return '';
}
echo $this->body;
}
|
php
|
public function send()
{
$this->sendCookies();
$this->sendHeaders();
if ($this->request->server('REQUEST_METHOD') === 'HEAD') {
return '';
}
echo $this->body;
}
|
Sends the response to the client
|
https://github.com/CodeCollab/Http/blob/b1f8306b20daebcf26ed4b13c032c5bc008a0861/src/Response/Response.php#L135-L146
|
CodeCollab/Http
|
src/Response/Response.php
|
Response.sendHeaders
|
private function sendHeaders()
{
if (!array_key_exists('Content-Type', $this->headers)) {
$this->headers['Content-Type'] = 'text/html; charset=UTF-8';
}
$this->headers['Content-Length'] = strlen($this->body);
header(
sprintf(
'HTTP/%s %s %s',
$this->request->server('SERVER_PROTOCOL'),
$this->numericStatusCode,
$this->textualStatusCode ?: $this->statusCode->getText($this->numericStatusCode)
),
true,
$this->numericStatusCode
);
foreach ($this->headers as $key => $value) {
header(sprintf('%s: %s', $key, $value));
}
}
|
php
|
private function sendHeaders()
{
if (!array_key_exists('Content-Type', $this->headers)) {
$this->headers['Content-Type'] = 'text/html; charset=UTF-8';
}
$this->headers['Content-Length'] = strlen($this->body);
header(
sprintf(
'HTTP/%s %s %s',
$this->request->server('SERVER_PROTOCOL'),
$this->numericStatusCode,
$this->textualStatusCode ?: $this->statusCode->getText($this->numericStatusCode)
),
true,
$this->numericStatusCode
);
foreach ($this->headers as $key => $value) {
header(sprintf('%s: %s', $key, $value));
}
}
|
Sends the headers to the client
|
https://github.com/CodeCollab/Http/blob/b1f8306b20daebcf26ed4b13c032c5bc008a0861/src/Response/Response.php#L161-L183
|
3ev/wordpress-core
|
src/Tev/Post/Model/Attachment.php
|
Attachment.getImageUrl
|
public function getImageUrl($size = 'thumbnail')
{
$res = wp_get_attachment_image_src($this->getId(), $size);
return $res && isset($res[0]) ? $res[0] : null;
}
|
php
|
public function getImageUrl($size = 'thumbnail')
{
$res = wp_get_attachment_image_src($this->getId(), $size);
return $res && isset($res[0]) ? $res[0] : null;
}
|
Get attachment image URL.
@param mixed $size Arguments accepted by second param of wp_get_attachment_image_src()
@return string|null Image URL or null if not found
|
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Post/Model/Attachment.php#L36-L40
|
courtney-miles/schnoop-schema
|
src/MySQL/Constraint/UniqueIndex.php
|
UniqueIndex.getDDL
|
public function getDDL()
{
if (strcasecmp('primary', $this->getName()) == 0) {
return $this->makeIndexDDL('PRIMARY KEY', null);
}
return $this->makeIndexDDL($this->getConstraintType(), $this->getName());
}
|
php
|
public function getDDL()
{
if (strcasecmp('primary', $this->getName()) == 0) {
return $this->makeIndexDDL('PRIMARY KEY', null);
}
return $this->makeIndexDDL($this->getConstraintType(), $this->getName());
}
|
{@inheritdoc}
|
https://github.com/courtney-miles/schnoop-schema/blob/f96e9922257860171ecdcdbb6b78182276e2f60d/src/MySQL/Constraint/UniqueIndex.php#L27-L34
|
chilimatic/chilimatic-framework
|
lib/handler/memory/shmop/Entry.php
|
Entry.save
|
public function save()
{
if ($this->id) {
$this->id = shmop_open($this->key, $this->mode, $this->permission, $this->size);
}
@shmop_write($this->id, serialize($this->data), $this->offset);
return true;
}
|
php
|
public function save()
{
if ($this->id) {
$this->id = shmop_open($this->key, $this->mode, $this->permission, $this->size);
}
@shmop_write($this->id, serialize($this->data), $this->offset);
return true;
}
|
saves the data of an entry
@return boolean
|
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/handler/memory/shmop/Entry.php#L160-L170
|
chilimatic/chilimatic-framework
|
lib/handler/memory/shmop/Entry.php
|
Entry.delete
|
public function delete()
{
if (empty($this->id)) {
$this->id = shmop_open($this->key, $this->mode, $this->permission, $this->size);
}
@shmop_delete($this->id);
@shmop_close($this->id);
return true;
}
|
php
|
public function delete()
{
if (empty($this->id)) {
$this->id = shmop_open($this->key, $this->mode, $this->permission, $this->size);
}
@shmop_delete($this->id);
@shmop_close($this->id);
return true;
}
|
deletes the entry
@return boolean
|
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/handler/memory/shmop/Entry.php#L209-L219
|
morrislaptop/error-tracker-adapter
|
src/ExceptionHandler.php
|
ExceptionHandler.handleShutdown
|
public function handleShutdown()
{
if (! is_null($error = error_get_last()) && $this->isFatal($error['type'])) {
$exception = new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']);
$this->handleException($exception);
}
}
|
php
|
public function handleShutdown()
{
if (! is_null($error = error_get_last()) && $this->isFatal($error['type'])) {
$exception = new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']);
$this->handleException($exception);
}
}
|
Handle the PHP shutdown event.
@return void
|
https://github.com/morrislaptop/error-tracker-adapter/blob/955aea67c45892da2b8813517600f338bada6a01/src/ExceptionHandler.php#L73-L79
|
temp/media-converter
|
src/Extractor/ExiftoolImageExtractor.php
|
ExiftoolImageExtractor.extract
|
public function extract($filename, Specification $targetFormat)
{
if (!file_exists($filename)) {
return null;
}
$metadatas = $this->reader->files($filename)->first();
$imageFilename = $this->tempDir . '/' . uniqid() . '.jpg';
foreach ($metadatas->getMetadatas() as $metadata) {
if ($metadata->getTag()->getName() !== 'Picture' &&
ValueInterface::TYPE_BINARY !== $metadata->getValue()->getType()) {
continue;
}
$filesystem = new Filesystem();
if (!$filesystem->exists($this->tempDir)) {
$filesystem->mkdir($this->tempDir);
}
$content = (string) $metadata->getValue()->asString();
$filesystem->dumpFile($imageFilename, $content);
return $imageFilename;
}
return null;
}
|
php
|
public function extract($filename, Specification $targetFormat)
{
if (!file_exists($filename)) {
return null;
}
$metadatas = $this->reader->files($filename)->first();
$imageFilename = $this->tempDir . '/' . uniqid() . '.jpg';
foreach ($metadatas->getMetadatas() as $metadata) {
if ($metadata->getTag()->getName() !== 'Picture' &&
ValueInterface::TYPE_BINARY !== $metadata->getValue()->getType()) {
continue;
}
$filesystem = new Filesystem();
if (!$filesystem->exists($this->tempDir)) {
$filesystem->mkdir($this->tempDir);
}
$content = (string) $metadata->getValue()->asString();
$filesystem->dumpFile($imageFilename, $content);
return $imageFilename;
}
return null;
}
|
{@inheritdoc}
|
https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Extractor/ExiftoolImageExtractor.php#L58-L87
|
borobudur-php/borobudur
|
src/Borobudur/Component/Ddd/Collection.php
|
Collection.find
|
public function find(Identifier $id): ?Model
{
$filtered = $this->filter(
function (Model $model) use ($id) {
return $model->getId()->equals($id);
}
);
if ($filtered->count()) {
return $filtered->first();
}
return null;
}
|
php
|
public function find(Identifier $id): ?Model
{
$filtered = $this->filter(
function (Model $model) use ($id) {
return $model->getId()->equals($id);
}
);
if ($filtered->count()) {
return $filtered->first();
}
return null;
}
|
{@inheritdoc}
|
https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Ddd/Collection.php#L26-L39
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.