repo
stringlengths 6
63
| path
stringlengths 5
140
| func_name
stringlengths 3
151
| original_string
stringlengths 84
13k
| language
stringclasses 1
value | code
stringlengths 84
13k
| code_tokens
list | docstring
stringlengths 3
47.2k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 91
247
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
frankkessler/guzzle-oauth2-middleware | src/Oauth2Client.php | Oauth2Client.getAccessToken | public function getAccessToken()
{
if ($this->accessToken && $this->accessToken->isExpired()) {
// The access token has expired.
$this->accessToken = null;
}
if (null === $this->accessToken) {
// Try to acquire a new access token from the server.
$this->accessToken = $this->acquireAccessToken();
if ($this->accessToken) {
$this->refreshToken = $this->accessToken->getRefreshToken() ?: null;
}
}
return $this->accessToken;
} | php | public function getAccessToken()
{
if ($this->accessToken && $this->accessToken->isExpired()) {
// The access token has expired.
$this->accessToken = null;
}
if (null === $this->accessToken) {
// Try to acquire a new access token from the server.
$this->accessToken = $this->acquireAccessToken();
if ($this->accessToken) {
$this->refreshToken = $this->accessToken->getRefreshToken() ?: null;
}
}
return $this->accessToken;
} | [
"public",
"function",
"getAccessToken",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"accessToken",
"&&",
"$",
"this",
"->",
"accessToken",
"->",
"isExpired",
"(",
")",
")",
"{",
"// The access token has expired.",
"$",
"this",
"->",
"accessToken",
"=",
"null",
";",
"}",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"accessToken",
")",
"{",
"// Try to acquire a new access token from the server.",
"$",
"this",
"->",
"accessToken",
"=",
"$",
"this",
"->",
"acquireAccessToken",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"accessToken",
")",
"{",
"$",
"this",
"->",
"refreshToken",
"=",
"$",
"this",
"->",
"accessToken",
"->",
"getRefreshToken",
"(",
")",
"?",
":",
"null",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"accessToken",
";",
"}"
]
| Get the access token.
@return AccessToken|null Oauth2 access token | [
"Get",
"the",
"access",
"token",
"."
]
| 00c0dd4093887f1921faa06cbbf0b5919ad5ad03 | https://github.com/frankkessler/guzzle-oauth2-middleware/blob/00c0dd4093887f1921faa06cbbf0b5919ad5ad03/src/Oauth2Client.php#L138-L154 | train |
shkdee/KeePassPHP | keepassphp/lib/group.php | Group.addGroup | private function addGroup($group)
{
if($group != null)
{
if($this->groups == null)
$this->groups = array();
$this->groups[] = $group;
}
} | php | private function addGroup($group)
{
if($group != null)
{
if($this->groups == null)
$this->groups = array();
$this->groups[] = $group;
}
} | [
"private",
"function",
"addGroup",
"(",
"$",
"group",
")",
"{",
"if",
"(",
"$",
"group",
"!=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"groups",
"==",
"null",
")",
"$",
"this",
"->",
"groups",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"groups",
"[",
"]",
"=",
"$",
"group",
";",
"}",
"}"
]
| Adds a Group instance as a sub-group of this group.
@param $entry A Group instance, possibly null (it is then ignored). | [
"Adds",
"a",
"Group",
"instance",
"as",
"a",
"sub",
"-",
"group",
"of",
"this",
"group",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/group.php#L84-L92 | train |
shkdee/KeePassPHP | keepassphp/lib/group.php | Group.addEntry | private function addEntry($entry)
{
if($entry != null)
{
if($this->entries == null)
$this->entries = array();
$this->entries[] = $entry;
}
} | php | private function addEntry($entry)
{
if($entry != null)
{
if($this->entries == null)
$this->entries = array();
$this->entries[] = $entry;
}
} | [
"private",
"function",
"addEntry",
"(",
"$",
"entry",
")",
"{",
"if",
"(",
"$",
"entry",
"!=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"entries",
"==",
"null",
")",
"$",
"this",
"->",
"entries",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"entries",
"[",
"]",
"=",
"$",
"entry",
";",
"}",
"}"
]
| Adds an Entry instance to this group.
@param $entry An Entry instance, possibly null (it is then ignored). | [
"Adds",
"an",
"Entry",
"instance",
"to",
"this",
"group",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/group.php#L98-L106 | train |
shkdee/KeePassPHP | keepassphp/lib/group.php | Group.loadFromXML | public static function loadFromXML(ProtectedXMLReader $reader)
{
if($reader == null)
return null;
$group = new Group();
$d = $reader->depth();
while($reader->read($d))
{
if($reader->isElement(Database::XML_GROUP))
$group->addGroup(Group::loadFromXML($reader));
elseif($reader->isElement(Database::XML_ENTRY))
$group->addEntry(Entry::loadFromXML($reader));
elseif($reader->isElement(Database::XML_UUID))
$group->uuid = $reader->readTextInside();
elseif($reader->isElement(Database::XML_NAME))
$group->name = $reader->readTextInside();
elseif($reader->isElement(Database::XML_ICONID))
$group->icon = $reader->readTextInside();
elseif($reader->isElement(Database::XML_CUSTOMICONUUID))
$group->customIcon = $reader->readTextInside();
}
return $group;
} | php | public static function loadFromXML(ProtectedXMLReader $reader)
{
if($reader == null)
return null;
$group = new Group();
$d = $reader->depth();
while($reader->read($d))
{
if($reader->isElement(Database::XML_GROUP))
$group->addGroup(Group::loadFromXML($reader));
elseif($reader->isElement(Database::XML_ENTRY))
$group->addEntry(Entry::loadFromXML($reader));
elseif($reader->isElement(Database::XML_UUID))
$group->uuid = $reader->readTextInside();
elseif($reader->isElement(Database::XML_NAME))
$group->name = $reader->readTextInside();
elseif($reader->isElement(Database::XML_ICONID))
$group->icon = $reader->readTextInside();
elseif($reader->isElement(Database::XML_CUSTOMICONUUID))
$group->customIcon = $reader->readTextInside();
}
return $group;
} | [
"public",
"static",
"function",
"loadFromXML",
"(",
"ProtectedXMLReader",
"$",
"reader",
")",
"{",
"if",
"(",
"$",
"reader",
"==",
"null",
")",
"return",
"null",
";",
"$",
"group",
"=",
"new",
"Group",
"(",
")",
";",
"$",
"d",
"=",
"$",
"reader",
"->",
"depth",
"(",
")",
";",
"while",
"(",
"$",
"reader",
"->",
"read",
"(",
"$",
"d",
")",
")",
"{",
"if",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_GROUP",
")",
")",
"$",
"group",
"->",
"addGroup",
"(",
"Group",
"::",
"loadFromXML",
"(",
"$",
"reader",
")",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_ENTRY",
")",
")",
"$",
"group",
"->",
"addEntry",
"(",
"Entry",
"::",
"loadFromXML",
"(",
"$",
"reader",
")",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_UUID",
")",
")",
"$",
"group",
"->",
"uuid",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_NAME",
")",
")",
"$",
"group",
"->",
"name",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_ICONID",
")",
")",
"$",
"group",
"->",
"icon",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_CUSTOMICONUUID",
")",
")",
"$",
"group",
"->",
"customIcon",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
";",
"}",
"return",
"$",
"group",
";",
"}"
]
| Creates a new Group instance from a ProtectedXMLReader instance reading
a KeePass 2.x database and located at a Group element node.
@param $reader A XML reader.
@return A Group instance if the parsing went okay, null otherwise. | [
"Creates",
"a",
"new",
"Group",
"instance",
"from",
"a",
"ProtectedXMLReader",
"instance",
"reading",
"a",
"KeePass",
"2",
".",
"x",
"database",
"and",
"located",
"at",
"a",
"Group",
"element",
"node",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/group.php#L188-L210 | train |
shkdee/KeePassPHP | keepassphp/util/salsa20stream.php | Salsa20Stream.create | public static function create($key, $iv)
{
if (strlen($key) != self::KEY_LEN || strlen($iv) != self::IV_LEN)
return null;
return new Salsa20Stream($key, $iv);
} | php | public static function create($key, $iv)
{
if (strlen($key) != self::KEY_LEN || strlen($iv) != self::IV_LEN)
return null;
return new Salsa20Stream($key, $iv);
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"key",
",",
"$",
"iv",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"key",
")",
"!=",
"self",
"::",
"KEY_LEN",
"||",
"strlen",
"(",
"$",
"iv",
")",
"!=",
"self",
"::",
"IV_LEN",
")",
"return",
"null",
";",
"return",
"new",
"Salsa20Stream",
"(",
"$",
"key",
",",
"$",
"iv",
")",
";",
"}"
]
| Creates a new Salsa20Stream instance.
@param $key The 32-byte-long string to use as key.
@param $iv The 8-byte-long string to use as initialization vector.
@return A new Salsa20Stream instance, of null if $key or $iv do not have
a suitable length. | [
"Creates",
"a",
"new",
"Salsa20Stream",
"instance",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/util/salsa20stream.php#L47-L52 | train |
shkdee/KeePassPHP | keepassphp/lib/kphpdb.php | KphpDB.createFromDatabase | public static function createFromDatabase(Database $db, $dbFileHash,
$keyFileHash)
{
return new KphpDB(self::DBTYPE_KDBX, $db, $dbFileHash, $keyFileHash);
} | php | public static function createFromDatabase(Database $db, $dbFileHash,
$keyFileHash)
{
return new KphpDB(self::DBTYPE_KDBX, $db, $dbFileHash, $keyFileHash);
} | [
"public",
"static",
"function",
"createFromDatabase",
"(",
"Database",
"$",
"db",
",",
"$",
"dbFileHash",
",",
"$",
"keyFileHash",
")",
"{",
"return",
"new",
"KphpDB",
"(",
"self",
"::",
"DBTYPE_KDBX",
",",
"$",
"db",
",",
"$",
"dbFileHash",
",",
"$",
"keyFileHash",
")",
";",
"}"
]
| Creates a new KphpDB instance that wraps a Database instance.
@param $db A Database instance.
@param $dbFileHash The hexadecimal hash of the original db file.
@param $keyFileHash A possible hexadecimal hash of an additional key
file if needed to decrypt the original db file.
@return A new KphpDB instance. | [
"Creates",
"a",
"new",
"KphpDB",
"instance",
"that",
"wraps",
"a",
"Database",
"instance",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/kphpdb.php#L71-L75 | train |
shkdee/KeePassPHP | keepassphp/lib/kphpdb.php | KphpDB.toJSon | public function toJSon($filter, &$error)
{
$array = array(
self::KEY_VERSION => self::VERSION_CURRENT,
self::KEY_DBTYPE => $this->_dbType,
self::KEY_DBFILEHASH => $this->_dbFileHash,
self::KEY_KEYFILEHASH => $this->_keyFileHash,
self::KEY_HEADERHASH => base64_encode($this->_headerHash),
self::KEY_DB => $this->_db->toArray($filter));
$r = json_encode($array);
if($r === false)
{
$error = "KphpDB JSon save: " . json_last_error();
return null;
}
$error = null;
return $r;
} | php | public function toJSon($filter, &$error)
{
$array = array(
self::KEY_VERSION => self::VERSION_CURRENT,
self::KEY_DBTYPE => $this->_dbType,
self::KEY_DBFILEHASH => $this->_dbFileHash,
self::KEY_KEYFILEHASH => $this->_keyFileHash,
self::KEY_HEADERHASH => base64_encode($this->_headerHash),
self::KEY_DB => $this->_db->toArray($filter));
$r = json_encode($array);
if($r === false)
{
$error = "KphpDB JSon save: " . json_last_error();
return null;
}
$error = null;
return $r;
} | [
"public",
"function",
"toJSon",
"(",
"$",
"filter",
",",
"&",
"$",
"error",
")",
"{",
"$",
"array",
"=",
"array",
"(",
"self",
"::",
"KEY_VERSION",
"=>",
"self",
"::",
"VERSION_CURRENT",
",",
"self",
"::",
"KEY_DBTYPE",
"=>",
"$",
"this",
"->",
"_dbType",
",",
"self",
"::",
"KEY_DBFILEHASH",
"=>",
"$",
"this",
"->",
"_dbFileHash",
",",
"self",
"::",
"KEY_KEYFILEHASH",
"=>",
"$",
"this",
"->",
"_keyFileHash",
",",
"self",
"::",
"KEY_HEADERHASH",
"=>",
"base64_encode",
"(",
"$",
"this",
"->",
"_headerHash",
")",
",",
"self",
"::",
"KEY_DB",
"=>",
"$",
"this",
"->",
"_db",
"->",
"toArray",
"(",
"$",
"filter",
")",
")",
";",
"$",
"r",
"=",
"json_encode",
"(",
"$",
"array",
")",
";",
"if",
"(",
"$",
"r",
"===",
"false",
")",
"{",
"$",
"error",
"=",
"\"KphpDB JSon save: \"",
".",
"json_last_error",
"(",
")",
";",
"return",
"null",
";",
"}",
"$",
"error",
"=",
"null",
";",
"return",
"$",
"r",
";",
"}"
]
| Serializes this instance to a JSon string.
@param $filter An iFilter instance to select the data of the database
that must actually be serialized (if null, it will
serialize everything except from passowrds).
@param &$error A string that will receive a message in case of error.
@return A JSon string in case of success, or null in case of error. | [
"Serializes",
"this",
"instance",
"to",
"a",
"JSon",
"string",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/kphpdb.php#L135-L152 | train |
shkdee/KeePassPHP | keepassphp/lib/kphpdb.php | KphpDB.toKdbx | public function toKdbx(iKey $key, $filter, &$error)
{
$kdbx = KdbxFile::createForEncrypting(self::ROUNDS, $error);
if($kdbx == null)
return null;
$this->_headerHash = $kdbx->getHeaderHash();
$json = $this->toJSon($filter, $error);
if(empty($json))
return null;
return $kdbx->encrypt($json, $key, $error);
} | php | public function toKdbx(iKey $key, $filter, &$error)
{
$kdbx = KdbxFile::createForEncrypting(self::ROUNDS, $error);
if($kdbx == null)
return null;
$this->_headerHash = $kdbx->getHeaderHash();
$json = $this->toJSon($filter, $error);
if(empty($json))
return null;
return $kdbx->encrypt($json, $key, $error);
} | [
"public",
"function",
"toKdbx",
"(",
"iKey",
"$",
"key",
",",
"$",
"filter",
",",
"&",
"$",
"error",
")",
"{",
"$",
"kdbx",
"=",
"KdbxFile",
"::",
"createForEncrypting",
"(",
"self",
"::",
"ROUNDS",
",",
"$",
"error",
")",
";",
"if",
"(",
"$",
"kdbx",
"==",
"null",
")",
"return",
"null",
";",
"$",
"this",
"->",
"_headerHash",
"=",
"$",
"kdbx",
"->",
"getHeaderHash",
"(",
")",
";",
"$",
"json",
"=",
"$",
"this",
"->",
"toJSon",
"(",
"$",
"filter",
",",
"$",
"error",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"json",
")",
")",
"return",
"null",
";",
"return",
"$",
"kdbx",
"->",
"encrypt",
"(",
"$",
"json",
",",
"$",
"key",
",",
"$",
"error",
")",
";",
"}"
]
| Serializes this instance to a JSon string and encrypts it in a kdbx
file.
@param $key A iKey instance to use to encrypt the kdbx file.
@param $filter An iFilter instance to select the data of the database
that must actually be serialized (if null, it will
serialize everything except from passowrds).
@param &$error A string that will receive a message in case of error.
@return A string containing a kdbx file embbeding this serialized
instance, or null in case of error. | [
"Serializes",
"this",
"instance",
"to",
"a",
"JSon",
"string",
"and",
"encrypts",
"it",
"in",
"a",
"kdbx",
"file",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/kphpdb.php#L165-L178 | train |
shkdee/KeePassPHP | keepassphp/lib/protectedxmlreader.php | ProtectedXMLReader.readTextInside | public function readTextInside($asProtectedString = false)
{
if($this->_state != self::GO_ON || $this->r->isEmptyElement)
return null;
$isProtected = $this->r->hasAttributes &&
$this->r->getAttribute(self::XML_ATTR_PROTECTED) == self::XML_ATTR_TRUE;
if(!@$this->r->read())
{
$this->_state = self::STOP;
return null;
}
if($this->r->nodeType == \XMLReader::TEXT)
{
$value = $this->r->value;
if(!$isProtected || empty($value) || $this->_randomStream == null)
return $asProtectedString
? new UnprotectedString($value)
: $value;
$value = base64_decode($value);
$random = $this->_randomStream->getNextBytes(strlen($value));
return $asProtectedString
? new ProtectedString($value, $random)
: $value ^ $random;
}
elseif($this->r->nodeType == \XMLReader::ELEMENT)
{
$this->_state = self::DO_NOT_READ;
return null;
}
} | php | public function readTextInside($asProtectedString = false)
{
if($this->_state != self::GO_ON || $this->r->isEmptyElement)
return null;
$isProtected = $this->r->hasAttributes &&
$this->r->getAttribute(self::XML_ATTR_PROTECTED) == self::XML_ATTR_TRUE;
if(!@$this->r->read())
{
$this->_state = self::STOP;
return null;
}
if($this->r->nodeType == \XMLReader::TEXT)
{
$value = $this->r->value;
if(!$isProtected || empty($value) || $this->_randomStream == null)
return $asProtectedString
? new UnprotectedString($value)
: $value;
$value = base64_decode($value);
$random = $this->_randomStream->getNextBytes(strlen($value));
return $asProtectedString
? new ProtectedString($value, $random)
: $value ^ $random;
}
elseif($this->r->nodeType == \XMLReader::ELEMENT)
{
$this->_state = self::DO_NOT_READ;
return null;
}
} | [
"public",
"function",
"readTextInside",
"(",
"$",
"asProtectedString",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_state",
"!=",
"self",
"::",
"GO_ON",
"||",
"$",
"this",
"->",
"r",
"->",
"isEmptyElement",
")",
"return",
"null",
";",
"$",
"isProtected",
"=",
"$",
"this",
"->",
"r",
"->",
"hasAttributes",
"&&",
"$",
"this",
"->",
"r",
"->",
"getAttribute",
"(",
"self",
"::",
"XML_ATTR_PROTECTED",
")",
"==",
"self",
"::",
"XML_ATTR_TRUE",
";",
"if",
"(",
"!",
"@",
"$",
"this",
"->",
"r",
"->",
"read",
"(",
")",
")",
"{",
"$",
"this",
"->",
"_state",
"=",
"self",
"::",
"STOP",
";",
"return",
"null",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"r",
"->",
"nodeType",
"==",
"\\",
"XMLReader",
"::",
"TEXT",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"r",
"->",
"value",
";",
"if",
"(",
"!",
"$",
"isProtected",
"||",
"empty",
"(",
"$",
"value",
")",
"||",
"$",
"this",
"->",
"_randomStream",
"==",
"null",
")",
"return",
"$",
"asProtectedString",
"?",
"new",
"UnprotectedString",
"(",
"$",
"value",
")",
":",
"$",
"value",
";",
"$",
"value",
"=",
"base64_decode",
"(",
"$",
"value",
")",
";",
"$",
"random",
"=",
"$",
"this",
"->",
"_randomStream",
"->",
"getNextBytes",
"(",
"strlen",
"(",
"$",
"value",
")",
")",
";",
"return",
"$",
"asProtectedString",
"?",
"new",
"ProtectedString",
"(",
"$",
"value",
",",
"$",
"random",
")",
":",
"$",
"value",
"^",
"$",
"random",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"r",
"->",
"nodeType",
"==",
"\\",
"XMLReader",
"::",
"ELEMENT",
")",
"{",
"$",
"this",
"->",
"_state",
"=",
"self",
"::",
"DO_NOT_READ",
";",
"return",
"null",
";",
"}",
"}"
]
| Reads the text content of the current Element node.
@param $asProtectedString Whether to return an iBoxedString instance
rather than a plain string.
@return The text content if it exists, or null. | [
"Reads",
"the",
"text",
"content",
"of",
"the",
"current",
"Element",
"node",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/protectedxmlreader.php#L123-L154 | train |
shkdee/KeePassPHP | keepassphp/lib/database.php | Database.addGroup | private function addGroup($group)
{
if($group != null)
{
if($this->_groups == null)
$this->_groups = array();
$this->_groups[] = $group;
}
} | php | private function addGroup($group)
{
if($group != null)
{
if($this->_groups == null)
$this->_groups = array();
$this->_groups[] = $group;
}
} | [
"private",
"function",
"addGroup",
"(",
"$",
"group",
")",
"{",
"if",
"(",
"$",
"group",
"!=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_groups",
"==",
"null",
")",
"$",
"this",
"->",
"_groups",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"_groups",
"[",
"]",
"=",
"$",
"group",
";",
"}",
"}"
]
| Adds a Group instance to this Database.
@param $entry A Group instance, possibly null (it is then ignored). | [
"Adds",
"a",
"Group",
"instance",
"to",
"this",
"Database",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/database.php#L139-L147 | train |
shkdee/KeePassPHP | keepassphp/lib/database.php | Database.parseXML | private function parseXML(ProtectedXMLReader $reader)
{
$d = $reader->depth();
while($reader->read($d))
{
if($reader->isElement(self::XML_META))
{
$metaD = $reader->depth();
while($reader->read($metaD))
{
if($reader->isElement(self::XML_HEADERHASH))
$this->_headerHash = base64_decode($reader->readTextInside());
elseif($reader->isElement(self::XML_DATABASENAME))
$this->_name = $reader->readTextInside();
elseif($reader->isElement(self::XML_CUSTOMICONS))
{
$iconsD = $reader->depth();
while($reader->read($iconsD))
{
if($reader->isElement(self::XML_ICON))
$this->parseCustomIcon($reader);
}
}
}
}
elseif($reader->isElement(self::XML_ROOT))
{
$rootD = $reader->depth();
while($reader->read($rootD))
{
if($reader->isElement(self::XML_GROUP))
$this->addGroup(Group::loadFromXML($reader));
}
}
}
} | php | private function parseXML(ProtectedXMLReader $reader)
{
$d = $reader->depth();
while($reader->read($d))
{
if($reader->isElement(self::XML_META))
{
$metaD = $reader->depth();
while($reader->read($metaD))
{
if($reader->isElement(self::XML_HEADERHASH))
$this->_headerHash = base64_decode($reader->readTextInside());
elseif($reader->isElement(self::XML_DATABASENAME))
$this->_name = $reader->readTextInside();
elseif($reader->isElement(self::XML_CUSTOMICONS))
{
$iconsD = $reader->depth();
while($reader->read($iconsD))
{
if($reader->isElement(self::XML_ICON))
$this->parseCustomIcon($reader);
}
}
}
}
elseif($reader->isElement(self::XML_ROOT))
{
$rootD = $reader->depth();
while($reader->read($rootD))
{
if($reader->isElement(self::XML_GROUP))
$this->addGroup(Group::loadFromXML($reader));
}
}
}
} | [
"private",
"function",
"parseXML",
"(",
"ProtectedXMLReader",
"$",
"reader",
")",
"{",
"$",
"d",
"=",
"$",
"reader",
"->",
"depth",
"(",
")",
";",
"while",
"(",
"$",
"reader",
"->",
"read",
"(",
"$",
"d",
")",
")",
"{",
"if",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"self",
"::",
"XML_META",
")",
")",
"{",
"$",
"metaD",
"=",
"$",
"reader",
"->",
"depth",
"(",
")",
";",
"while",
"(",
"$",
"reader",
"->",
"read",
"(",
"$",
"metaD",
")",
")",
"{",
"if",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"self",
"::",
"XML_HEADERHASH",
")",
")",
"$",
"this",
"->",
"_headerHash",
"=",
"base64_decode",
"(",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"self",
"::",
"XML_DATABASENAME",
")",
")",
"$",
"this",
"->",
"_name",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"self",
"::",
"XML_CUSTOMICONS",
")",
")",
"{",
"$",
"iconsD",
"=",
"$",
"reader",
"->",
"depth",
"(",
")",
";",
"while",
"(",
"$",
"reader",
"->",
"read",
"(",
"$",
"iconsD",
")",
")",
"{",
"if",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"self",
"::",
"XML_ICON",
")",
")",
"$",
"this",
"->",
"parseCustomIcon",
"(",
"$",
"reader",
")",
";",
"}",
"}",
"}",
"}",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"self",
"::",
"XML_ROOT",
")",
")",
"{",
"$",
"rootD",
"=",
"$",
"reader",
"->",
"depth",
"(",
")",
";",
"while",
"(",
"$",
"reader",
"->",
"read",
"(",
"$",
"rootD",
")",
")",
"{",
"if",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"self",
"::",
"XML_GROUP",
")",
")",
"$",
"this",
"->",
"addGroup",
"(",
"Group",
"::",
"loadFromXML",
"(",
"$",
"reader",
")",
")",
";",
"}",
"}",
"}",
"}"
]
| Loads the content of a Database from a ProtectedXMLReader instance
reading a KeePass 2.x database and located at a KeePass file element
node.
@param $reader A XML reader. | [
"Loads",
"the",
"content",
"of",
"a",
"Database",
"from",
"a",
"ProtectedXMLReader",
"instance",
"reading",
"a",
"KeePass",
"2",
".",
"x",
"database",
"and",
"located",
"at",
"a",
"KeePass",
"file",
"element",
"node",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/database.php#L155-L190 | train |
shkdee/KeePassPHP | keepassphp/lib/database.php | Database.loadFromXML | public static function loadFromXML($xml, iRandomStream $randomStream,
&$error)
{
$reader = new ProtectedXMLReader($randomStream);
if(!$reader->XML($xml) || !$reader->read(-1))
{
$error = "Database XML load: cannot parse the XML string.";
$reader->close();
return null;
}
if(!$reader->isElement(self::XML_KEEPASSFILE))
{
$error = "Database XML load: the root element is not '" . self::XML_KEEPASSFILE . "'.";
$reader->close();
return null;
}
$db = new Database();
$db->parseXML($reader);
$reader->close();
if($db->_name == null && $db->_groups == null)
{
$error = "Database XML load: empty database.";
return null;
}
$error = null;
return $db;
} | php | public static function loadFromXML($xml, iRandomStream $randomStream,
&$error)
{
$reader = new ProtectedXMLReader($randomStream);
if(!$reader->XML($xml) || !$reader->read(-1))
{
$error = "Database XML load: cannot parse the XML string.";
$reader->close();
return null;
}
if(!$reader->isElement(self::XML_KEEPASSFILE))
{
$error = "Database XML load: the root element is not '" . self::XML_KEEPASSFILE . "'.";
$reader->close();
return null;
}
$db = new Database();
$db->parseXML($reader);
$reader->close();
if($db->_name == null && $db->_groups == null)
{
$error = "Database XML load: empty database.";
return null;
}
$error = null;
return $db;
} | [
"public",
"static",
"function",
"loadFromXML",
"(",
"$",
"xml",
",",
"iRandomStream",
"$",
"randomStream",
",",
"&",
"$",
"error",
")",
"{",
"$",
"reader",
"=",
"new",
"ProtectedXMLReader",
"(",
"$",
"randomStream",
")",
";",
"if",
"(",
"!",
"$",
"reader",
"->",
"XML",
"(",
"$",
"xml",
")",
"||",
"!",
"$",
"reader",
"->",
"read",
"(",
"-",
"1",
")",
")",
"{",
"$",
"error",
"=",
"\"Database XML load: cannot parse the XML string.\"",
";",
"$",
"reader",
"->",
"close",
"(",
")",
";",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"$",
"reader",
"->",
"isElement",
"(",
"self",
"::",
"XML_KEEPASSFILE",
")",
")",
"{",
"$",
"error",
"=",
"\"Database XML load: the root element is not '\"",
".",
"self",
"::",
"XML_KEEPASSFILE",
".",
"\"'.\"",
";",
"$",
"reader",
"->",
"close",
"(",
")",
";",
"return",
"null",
";",
"}",
"$",
"db",
"=",
"new",
"Database",
"(",
")",
";",
"$",
"db",
"->",
"parseXML",
"(",
"$",
"reader",
")",
";",
"$",
"reader",
"->",
"close",
"(",
")",
";",
"if",
"(",
"$",
"db",
"->",
"_name",
"==",
"null",
"&&",
"$",
"db",
"->",
"_groups",
"==",
"null",
")",
"{",
"$",
"error",
"=",
"\"Database XML load: empty database.\"",
";",
"return",
"null",
";",
"}",
"$",
"error",
"=",
"null",
";",
"return",
"$",
"db",
";",
"}"
]
| Creates a new Database instance from an XML string with the format of
a KeePass 2.x database.
@param $xml An XML string.
@param $randomStream A iRandomStream instance to decrypt protected data.
@param &$error A string that will receive a message in case of error.
@return A Database instance if the parsing went okay, null otherwise. | [
"Creates",
"a",
"new",
"Database",
"instance",
"from",
"an",
"XML",
"string",
"with",
"the",
"format",
"of",
"a",
"KeePass",
"2",
".",
"x",
"database",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/database.php#L264-L290 | train |
shkdee/KeePassPHP | keepassphp/keepassphp.php | KeePassPHP.extractHalfPassword | public static function extractHalfPassword($pwd)
{
$l = strlen($pwd);
if($l < 4)
return $pwd;
else
return substr($pwd, 0, intval(floor($l/2)));
} | php | public static function extractHalfPassword($pwd)
{
$l = strlen($pwd);
if($l < 4)
return $pwd;
else
return substr($pwd, 0, intval(floor($l/2)));
} | [
"public",
"static",
"function",
"extractHalfPassword",
"(",
"$",
"pwd",
")",
"{",
"$",
"l",
"=",
"strlen",
"(",
"$",
"pwd",
")",
";",
"if",
"(",
"$",
"l",
"<",
"4",
")",
"return",
"$",
"pwd",
";",
"else",
"return",
"substr",
"(",
"$",
"pwd",
",",
"0",
",",
"intval",
"(",
"floor",
"(",
"$",
"l",
"/",
"2",
")",
")",
")",
";",
"}"
]
| Extracts a subpart of the input string if it long enough.
@param $pwd A password, that should be longer than 4 characters.
@return A subpart of the input string. | [
"Extracts",
"a",
"subpart",
"of",
"the",
"input",
"string",
"if",
"it",
"long",
"enough",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/keepassphp.php#L260-L267 | train |
shkdee/KeePassPHP | keepassphp/keepassphp.php | KeePassPHP.addPassword | public static function addPassword(CompositeKey $mkey, $pwd)
{
$mkey->addKey(self::keyFromPassword($pwd));
return true;
} | php | public static function addPassword(CompositeKey $mkey, $pwd)
{
$mkey->addKey(self::keyFromPassword($pwd));
return true;
} | [
"public",
"static",
"function",
"addPassword",
"(",
"CompositeKey",
"$",
"mkey",
",",
"$",
"pwd",
")",
"{",
"$",
"mkey",
"->",
"addKey",
"(",
"self",
"::",
"keyFromPassword",
"(",
"$",
"pwd",
")",
")",
";",
"return",
"true",
";",
"}"
]
| Adds a password to a master key.
@param $mkey A master key.
@param $pwd A text password.
@return true if the operation succeeded, false otherwise. | [
"Adds",
"a",
"password",
"to",
"a",
"master",
"key",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/keepassphp.php#L569-L573 | train |
shkdee/KeePassPHP | keepassphp/keepassphp.php | KeePassPHP.addKeyFile | public static function addKeyFile(CompositeKey $mkey, $file)
{
if(empty($file))
return true;
$k = new KeyFromFile(file_get_contents($file));
if(!$k->isParsed)
return false;
$mkey->addKey($k);
return true;
} | php | public static function addKeyFile(CompositeKey $mkey, $file)
{
if(empty($file))
return true;
$k = new KeyFromFile(file_get_contents($file));
if(!$k->isParsed)
return false;
$mkey->addKey($k);
return true;
} | [
"public",
"static",
"function",
"addKeyFile",
"(",
"CompositeKey",
"$",
"mkey",
",",
"$",
"file",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"file",
")",
")",
"return",
"true",
";",
"$",
"k",
"=",
"new",
"KeyFromFile",
"(",
"file_get_contents",
"(",
"$",
"file",
")",
")",
";",
"if",
"(",
"!",
"$",
"k",
"->",
"isParsed",
")",
"return",
"false",
";",
"$",
"mkey",
"->",
"addKey",
"(",
"$",
"k",
")",
";",
"return",
"true",
";",
"}"
]
| Adds a file key to a master key.
@param $mkey A master key.
@param $file The path of a file key.
@return true if the operation succeeded, false otherwise. | [
"Adds",
"a",
"file",
"key",
"to",
"a",
"master",
"key",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/keepassphp.php#L581-L590 | train |
shkdee/KeePassPHP | keepassphp/util/cipher.php | CipherMcrypt.setMethod | public function setMethod($method)
{
parent::setMethod($method);
$method = strtolower($method);
if($method == "aes-256-ecb")
{
$this->_type = MCRYPT_RIJNDAEL_128;
$this->_mode = "ecb";
}
elseif($method == "aes-256-cbc")
{
$this->_type = MCRYPT_RIJNDAEL_128;
$this->_mode = "cbc";
}
} | php | public function setMethod($method)
{
parent::setMethod($method);
$method = strtolower($method);
if($method == "aes-256-ecb")
{
$this->_type = MCRYPT_RIJNDAEL_128;
$this->_mode = "ecb";
}
elseif($method == "aes-256-cbc")
{
$this->_type = MCRYPT_RIJNDAEL_128;
$this->_mode = "cbc";
}
} | [
"public",
"function",
"setMethod",
"(",
"$",
"method",
")",
"{",
"parent",
"::",
"setMethod",
"(",
"$",
"method",
")",
";",
"$",
"method",
"=",
"strtolower",
"(",
"$",
"method",
")",
";",
"if",
"(",
"$",
"method",
"==",
"\"aes-256-ecb\"",
")",
"{",
"$",
"this",
"->",
"_type",
"=",
"MCRYPT_RIJNDAEL_128",
";",
"$",
"this",
"->",
"_mode",
"=",
"\"ecb\"",
";",
"}",
"elseif",
"(",
"$",
"method",
"==",
"\"aes-256-cbc\"",
")",
"{",
"$",
"this",
"->",
"_type",
"=",
"MCRYPT_RIJNDAEL_128",
";",
"$",
"this",
"->",
"_mode",
"=",
"\"cbc\"",
";",
"}",
"}"
]
| Sets the cipher method to use.
@param $method One of the OpenSSL ciphers constants. | [
"Sets",
"the",
"cipher",
"method",
"to",
"use",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/util/cipher.php#L237-L251 | train |
shkdee/KeePassPHP | keepassphp/util/cipher.php | CipherMcrypt.load | private function load()
{
if(strlen($this->_method) == 0 || strlen($this->_key) == 0)
return null;
$m = mcrypt_module_open($this->_type, '', $this->_mode, '');
if($m === false)
return null;
// This check is performed by mcrypt_generic_init, but it's better
// to do it now, because mcrypt_generic_init does not return a
// negative or false value if it fails.
$ivsize = mcrypt_enc_get_iv_size($m);
if(strlen($this->_iv) != $ivsize)
{
// In ECB (and some other modes), the IV is not used but still
// required to have the this size by mcrypt_generic_init, so
// let's make a fake one.
if(strtolower($this->_mode) == "ecb")
$ivsize = str_repeat("\0", $ivsize);
else
return null;
}
$r = @mcrypt_generic_init($m, $this->_key, $this->_iv);
if($r < 0 || $r === false)
return null;
return $m;
} | php | private function load()
{
if(strlen($this->_method) == 0 || strlen($this->_key) == 0)
return null;
$m = mcrypt_module_open($this->_type, '', $this->_mode, '');
if($m === false)
return null;
// This check is performed by mcrypt_generic_init, but it's better
// to do it now, because mcrypt_generic_init does not return a
// negative or false value if it fails.
$ivsize = mcrypt_enc_get_iv_size($m);
if(strlen($this->_iv) != $ivsize)
{
// In ECB (and some other modes), the IV is not used but still
// required to have the this size by mcrypt_generic_init, so
// let's make a fake one.
if(strtolower($this->_mode) == "ecb")
$ivsize = str_repeat("\0", $ivsize);
else
return null;
}
$r = @mcrypt_generic_init($m, $this->_key, $this->_iv);
if($r < 0 || $r === false)
return null;
return $m;
} | [
"private",
"function",
"load",
"(",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"this",
"->",
"_method",
")",
"==",
"0",
"||",
"strlen",
"(",
"$",
"this",
"->",
"_key",
")",
"==",
"0",
")",
"return",
"null",
";",
"$",
"m",
"=",
"mcrypt_module_open",
"(",
"$",
"this",
"->",
"_type",
",",
"''",
",",
"$",
"this",
"->",
"_mode",
",",
"''",
")",
";",
"if",
"(",
"$",
"m",
"===",
"false",
")",
"return",
"null",
";",
"// This check is performed by mcrypt_generic_init, but it's better\r",
"// to do it now, because mcrypt_generic_init does not return a\r",
"// negative or false value if it fails.\r",
"$",
"ivsize",
"=",
"mcrypt_enc_get_iv_size",
"(",
"$",
"m",
")",
";",
"if",
"(",
"strlen",
"(",
"$",
"this",
"->",
"_iv",
")",
"!=",
"$",
"ivsize",
")",
"{",
"// In ECB (and some other modes), the IV is not used but still\r",
"// required to have the this size by mcrypt_generic_init, so\r",
"// let's make a fake one.\r",
"if",
"(",
"strtolower",
"(",
"$",
"this",
"->",
"_mode",
")",
"==",
"\"ecb\"",
")",
"$",
"ivsize",
"=",
"str_repeat",
"(",
"\"\\0\"",
",",
"$",
"ivsize",
")",
";",
"else",
"return",
"null",
";",
"}",
"$",
"r",
"=",
"@",
"mcrypt_generic_init",
"(",
"$",
"m",
",",
"$",
"this",
"->",
"_key",
",",
"$",
"this",
"->",
"_iv",
")",
";",
"if",
"(",
"$",
"r",
"<",
"0",
"||",
"$",
"r",
"===",
"false",
")",
"return",
"null",
";",
"return",
"$",
"m",
";",
"}"
]
| Opens a mcrypt module.
@return A mcrypt module resource, or null if an error occurred. | [
"Opens",
"a",
"mcrypt",
"module",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/util/cipher.php#L316-L341 | train |
shkdee/KeePassPHP | keepassphp/lib/kdbxheader.php | KdbxHeader.toBinary | public function toBinary($hashAlgo)
{
$s = self::SIGNATURE1 . self::SIGNATURE2 . self::VERSION
. self::fieldToString(2, $this->cipher)
. self::fieldToString(3,
$this->compression == self::COMPRESSION_GZIP
? self::INT_1 : self::INT_0)
. self::fieldToString(4, $this->masterSeed)
. self::fieldToString(5, $this->transformSeed)
. self::fieldToString(6, $this->rounds)
. self::fieldToString(7, $this->encryptionIV)
. self::fieldToString(8, $this->randomStreamKey)
. self::fieldToString(9, $this->startBytes)
. self::fieldToString(10,
$this->randomStream == self::RANDOMSTREAM_SALSA20
? self::INT_2 : self::INT_0)
. self::fieldToString(0, null);
$this->headerHash = hash($hashAlgo, $s, true);
return $s;
} | php | public function toBinary($hashAlgo)
{
$s = self::SIGNATURE1 . self::SIGNATURE2 . self::VERSION
. self::fieldToString(2, $this->cipher)
. self::fieldToString(3,
$this->compression == self::COMPRESSION_GZIP
? self::INT_1 : self::INT_0)
. self::fieldToString(4, $this->masterSeed)
. self::fieldToString(5, $this->transformSeed)
. self::fieldToString(6, $this->rounds)
. self::fieldToString(7, $this->encryptionIV)
. self::fieldToString(8, $this->randomStreamKey)
. self::fieldToString(9, $this->startBytes)
. self::fieldToString(10,
$this->randomStream == self::RANDOMSTREAM_SALSA20
? self::INT_2 : self::INT_0)
. self::fieldToString(0, null);
$this->headerHash = hash($hashAlgo, $s, true);
return $s;
} | [
"public",
"function",
"toBinary",
"(",
"$",
"hashAlgo",
")",
"{",
"$",
"s",
"=",
"self",
"::",
"SIGNATURE1",
".",
"self",
"::",
"SIGNATURE2",
".",
"self",
"::",
"VERSION",
".",
"self",
"::",
"fieldToString",
"(",
"2",
",",
"$",
"this",
"->",
"cipher",
")",
".",
"self",
"::",
"fieldToString",
"(",
"3",
",",
"$",
"this",
"->",
"compression",
"==",
"self",
"::",
"COMPRESSION_GZIP",
"?",
"self",
"::",
"INT_1",
":",
"self",
"::",
"INT_0",
")",
".",
"self",
"::",
"fieldToString",
"(",
"4",
",",
"$",
"this",
"->",
"masterSeed",
")",
".",
"self",
"::",
"fieldToString",
"(",
"5",
",",
"$",
"this",
"->",
"transformSeed",
")",
".",
"self",
"::",
"fieldToString",
"(",
"6",
",",
"$",
"this",
"->",
"rounds",
")",
".",
"self",
"::",
"fieldToString",
"(",
"7",
",",
"$",
"this",
"->",
"encryptionIV",
")",
".",
"self",
"::",
"fieldToString",
"(",
"8",
",",
"$",
"this",
"->",
"randomStreamKey",
")",
".",
"self",
"::",
"fieldToString",
"(",
"9",
",",
"$",
"this",
"->",
"startBytes",
")",
".",
"self",
"::",
"fieldToString",
"(",
"10",
",",
"$",
"this",
"->",
"randomStream",
"==",
"self",
"::",
"RANDOMSTREAM_SALSA20",
"?",
"self",
"::",
"INT_2",
":",
"self",
"::",
"INT_0",
")",
".",
"self",
"::",
"fieldToString",
"(",
"0",
",",
"null",
")",
";",
"$",
"this",
"->",
"headerHash",
"=",
"hash",
"(",
"$",
"hashAlgo",
",",
"$",
"s",
",",
"true",
")",
";",
"return",
"$",
"s",
";",
"}"
]
| Gets the binary format of this Header instance, and computes its hash.
@param $hashAlgo The hash algorithm to use to compute the header hash.
@return A binary string representing this Header instance. | [
"Gets",
"the",
"binary",
"format",
"of",
"this",
"Header",
"instance",
"and",
"computes",
"its",
"hash",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/kdbxheader.php#L79-L98 | train |
shkdee/KeePassPHP | keepassphp/lib/kdbxheader.php | KdbxHeader.fieldToString | private static function fieldToString($id, $value)
{
$l = strlen($value);
return chr($id) . ($l == 0 ? "\x00\x00" : (pack("v", $l) . $value));
} | php | private static function fieldToString($id, $value)
{
$l = strlen($value);
return chr($id) . ($l == 0 ? "\x00\x00" : (pack("v", $l) . $value));
} | [
"private",
"static",
"function",
"fieldToString",
"(",
"$",
"id",
",",
"$",
"value",
")",
"{",
"$",
"l",
"=",
"strlen",
"(",
"$",
"value",
")",
";",
"return",
"chr",
"(",
"$",
"id",
")",
".",
"(",
"$",
"l",
"==",
"0",
"?",
"\"\\x00\\x00\"",
":",
"(",
"pack",
"(",
"\"v\"",
",",
"$",
"l",
")",
".",
"$",
"value",
")",
")",
";",
"}"
]
| Gets the binary format of the given header field.
@param $id The field id.
@param $value The field value.
@return A binary string representing the header field. | [
"Gets",
"the",
"binary",
"format",
"of",
"the",
"given",
"header",
"field",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/kdbxheader.php#L106-L110 | train |
shkdee/KeePassPHP | keepassphp/lib/kdbxheader.php | KdbxHeader.check | public function check()
{
if($this->cipher === null)
return false;
if($this->compression === 0)
return false;
if($this->masterSeed === null)
return false;
if($this->transformSeed === null)
return false;
if($this->rounds === null)
return false;
if($this->encryptionIV === null)
return false;
if($this->startBytes === null)
return false;
if($this->headerHash === null)
return false;
if($this->randomStreamKey === null)
return false;
if($this->randomStream === 0)
return false;
return true;
} | php | public function check()
{
if($this->cipher === null)
return false;
if($this->compression === 0)
return false;
if($this->masterSeed === null)
return false;
if($this->transformSeed === null)
return false;
if($this->rounds === null)
return false;
if($this->encryptionIV === null)
return false;
if($this->startBytes === null)
return false;
if($this->headerHash === null)
return false;
if($this->randomStreamKey === null)
return false;
if($this->randomStream === 0)
return false;
return true;
} | [
"public",
"function",
"check",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"cipher",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"compression",
"===",
"0",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"masterSeed",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"transformSeed",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"rounds",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"encryptionIV",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"startBytes",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"headerHash",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"randomStreamKey",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"randomStream",
"===",
"0",
")",
"return",
"false",
";",
"return",
"true",
";",
"}"
]
| Checks whether all fields are set in this instance.
@return true if all fields are set, false otherwise. | [
"Checks",
"whether",
"all",
"fields",
"are",
"set",
"in",
"this",
"instance",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/kdbxheader.php#L116-L139 | train |
shkdee/KeePassPHP | keepassphp/lib/kdbxheader.php | KdbxHeader.load | public static function load(Reader $reader, $hashAlgo, &$error)
{
$dreader = new DigestReader($reader, $hashAlgo);
$sig1 = $dreader->read(4);
$sig2 = $dreader->read(4);
if($sig1 != self::SIGNATURE1 || $sig2 != self::SIGNATURE2)
{
$error = "Kdbx header: signature not correct.";
return null;
}
$lowerversion = $dreader->readNumber(2);
$upperversion = $dreader->readNumber(2);
if($upperversion > self::MAXIMAL_VERSION)
{
$error = "Kdbx header: version not supported.";
return null;
}
$header = new KdbxHeader();
$ended = false;
while(!$ended)
{
$fieldId = $dreader->readByte();
$fieldLen = $dreader->readNumber(2);
$field = null;
if($fieldLen > 0)
{
$field = $dreader->read($fieldLen);
if($field == null || strlen($field) != $fieldLen)
{
$error = "Kdbx header: uncomplete header field.";
return null;
}
}
/*
* end of header
*/
if($fieldId == 0)
$ended = true;
/*
* comment (let's ignore)
*/
//elseif($fieldId == 1)
// ;
/*
* Cipher type
*/
elseif($fieldId == 2)
$header->cipher = $field;
/*
* Compression method
*/
elseif($fieldId == 3)
{
if($field == self::INT_0)
$header->compression = self::COMPRESSION_NONE;
elseif($field == self::INT_1)
$header->compression = self::COMPRESSION_GZIP;
}
/*
* MasterSeed
*/
elseif($fieldId == 4)
$header->masterSeed = $field;
/*
* TransformSeed
*/
elseif($fieldId == 5)
$header->transformSeed = $field;
/*
* Number of rounds
*/
elseif($fieldId == 6)
$header->rounds = $field;
/*
* EncryptionIV
*/
elseif($fieldId == 7)
$header->encryptionIV = $field;
/*
* Random stream key
*/
elseif($fieldId == 8)
$header->randomStreamKey = $field;
/*
* First bytes of result
*/
elseif($fieldId == 9)
$header->startBytes = $field;
/*
* Random stream type
*/
elseif($fieldId == 10)
{
if($field == self::INT_0)
$header->randomStream = self::RANDOMSTREAM_NONE;
elseif($field == self::INT_2)
$header->randomStream = self::RANDOMSTREAM_SALSA20;
/*elseif($field == self::INT_1) // unsuported
$header->randomStream= self::RANDOMSTREAM_ARC4;*/
}
}
$header->headerHash = $dreader->GetDigest();
$error = null;
return $header;
} | php | public static function load(Reader $reader, $hashAlgo, &$error)
{
$dreader = new DigestReader($reader, $hashAlgo);
$sig1 = $dreader->read(4);
$sig2 = $dreader->read(4);
if($sig1 != self::SIGNATURE1 || $sig2 != self::SIGNATURE2)
{
$error = "Kdbx header: signature not correct.";
return null;
}
$lowerversion = $dreader->readNumber(2);
$upperversion = $dreader->readNumber(2);
if($upperversion > self::MAXIMAL_VERSION)
{
$error = "Kdbx header: version not supported.";
return null;
}
$header = new KdbxHeader();
$ended = false;
while(!$ended)
{
$fieldId = $dreader->readByte();
$fieldLen = $dreader->readNumber(2);
$field = null;
if($fieldLen > 0)
{
$field = $dreader->read($fieldLen);
if($field == null || strlen($field) != $fieldLen)
{
$error = "Kdbx header: uncomplete header field.";
return null;
}
}
/*
* end of header
*/
if($fieldId == 0)
$ended = true;
/*
* comment (let's ignore)
*/
//elseif($fieldId == 1)
// ;
/*
* Cipher type
*/
elseif($fieldId == 2)
$header->cipher = $field;
/*
* Compression method
*/
elseif($fieldId == 3)
{
if($field == self::INT_0)
$header->compression = self::COMPRESSION_NONE;
elseif($field == self::INT_1)
$header->compression = self::COMPRESSION_GZIP;
}
/*
* MasterSeed
*/
elseif($fieldId == 4)
$header->masterSeed = $field;
/*
* TransformSeed
*/
elseif($fieldId == 5)
$header->transformSeed = $field;
/*
* Number of rounds
*/
elseif($fieldId == 6)
$header->rounds = $field;
/*
* EncryptionIV
*/
elseif($fieldId == 7)
$header->encryptionIV = $field;
/*
* Random stream key
*/
elseif($fieldId == 8)
$header->randomStreamKey = $field;
/*
* First bytes of result
*/
elseif($fieldId == 9)
$header->startBytes = $field;
/*
* Random stream type
*/
elseif($fieldId == 10)
{
if($field == self::INT_0)
$header->randomStream = self::RANDOMSTREAM_NONE;
elseif($field == self::INT_2)
$header->randomStream = self::RANDOMSTREAM_SALSA20;
/*elseif($field == self::INT_1) // unsuported
$header->randomStream= self::RANDOMSTREAM_ARC4;*/
}
}
$header->headerHash = $dreader->GetDigest();
$error = null;
return $header;
} | [
"public",
"static",
"function",
"load",
"(",
"Reader",
"$",
"reader",
",",
"$",
"hashAlgo",
",",
"&",
"$",
"error",
")",
"{",
"$",
"dreader",
"=",
"new",
"DigestReader",
"(",
"$",
"reader",
",",
"$",
"hashAlgo",
")",
";",
"$",
"sig1",
"=",
"$",
"dreader",
"->",
"read",
"(",
"4",
")",
";",
"$",
"sig2",
"=",
"$",
"dreader",
"->",
"read",
"(",
"4",
")",
";",
"if",
"(",
"$",
"sig1",
"!=",
"self",
"::",
"SIGNATURE1",
"||",
"$",
"sig2",
"!=",
"self",
"::",
"SIGNATURE2",
")",
"{",
"$",
"error",
"=",
"\"Kdbx header: signature not correct.\"",
";",
"return",
"null",
";",
"}",
"$",
"lowerversion",
"=",
"$",
"dreader",
"->",
"readNumber",
"(",
"2",
")",
";",
"$",
"upperversion",
"=",
"$",
"dreader",
"->",
"readNumber",
"(",
"2",
")",
";",
"if",
"(",
"$",
"upperversion",
">",
"self",
"::",
"MAXIMAL_VERSION",
")",
"{",
"$",
"error",
"=",
"\"Kdbx header: version not supported.\"",
";",
"return",
"null",
";",
"}",
"$",
"header",
"=",
"new",
"KdbxHeader",
"(",
")",
";",
"$",
"ended",
"=",
"false",
";",
"while",
"(",
"!",
"$",
"ended",
")",
"{",
"$",
"fieldId",
"=",
"$",
"dreader",
"->",
"readByte",
"(",
")",
";",
"$",
"fieldLen",
"=",
"$",
"dreader",
"->",
"readNumber",
"(",
"2",
")",
";",
"$",
"field",
"=",
"null",
";",
"if",
"(",
"$",
"fieldLen",
">",
"0",
")",
"{",
"$",
"field",
"=",
"$",
"dreader",
"->",
"read",
"(",
"$",
"fieldLen",
")",
";",
"if",
"(",
"$",
"field",
"==",
"null",
"||",
"strlen",
"(",
"$",
"field",
")",
"!=",
"$",
"fieldLen",
")",
"{",
"$",
"error",
"=",
"\"Kdbx header: uncomplete header field.\"",
";",
"return",
"null",
";",
"}",
"}",
"/*\n\t\t\t * end of header\n\t\t\t */",
"if",
"(",
"$",
"fieldId",
"==",
"0",
")",
"$",
"ended",
"=",
"true",
";",
"/*\n\t\t\t * comment (let's ignore)\n\t\t\t */",
"//elseif($fieldId == 1)",
"//\t;",
"/*\n\t\t\t * Cipher type\n\t\t\t */",
"elseif",
"(",
"$",
"fieldId",
"==",
"2",
")",
"$",
"header",
"->",
"cipher",
"=",
"$",
"field",
";",
"/*\n\t\t\t * Compression method\n\t\t\t */",
"elseif",
"(",
"$",
"fieldId",
"==",
"3",
")",
"{",
"if",
"(",
"$",
"field",
"==",
"self",
"::",
"INT_0",
")",
"$",
"header",
"->",
"compression",
"=",
"self",
"::",
"COMPRESSION_NONE",
";",
"elseif",
"(",
"$",
"field",
"==",
"self",
"::",
"INT_1",
")",
"$",
"header",
"->",
"compression",
"=",
"self",
"::",
"COMPRESSION_GZIP",
";",
"}",
"/*\n\t\t\t * MasterSeed\n\t\t\t */",
"elseif",
"(",
"$",
"fieldId",
"==",
"4",
")",
"$",
"header",
"->",
"masterSeed",
"=",
"$",
"field",
";",
"/*\n\t\t\t * TransformSeed\n\t\t\t */",
"elseif",
"(",
"$",
"fieldId",
"==",
"5",
")",
"$",
"header",
"->",
"transformSeed",
"=",
"$",
"field",
";",
"/*\n\t\t\t * Number of rounds\n\t\t\t */",
"elseif",
"(",
"$",
"fieldId",
"==",
"6",
")",
"$",
"header",
"->",
"rounds",
"=",
"$",
"field",
";",
"/*\n\t\t\t * EncryptionIV\n\t\t\t */",
"elseif",
"(",
"$",
"fieldId",
"==",
"7",
")",
"$",
"header",
"->",
"encryptionIV",
"=",
"$",
"field",
";",
"/*\n\t\t\t * Random stream key\n\t\t\t */",
"elseif",
"(",
"$",
"fieldId",
"==",
"8",
")",
"$",
"header",
"->",
"randomStreamKey",
"=",
"$",
"field",
";",
"/*\n\t\t\t * First bytes of result\n\t\t\t */",
"elseif",
"(",
"$",
"fieldId",
"==",
"9",
")",
"$",
"header",
"->",
"startBytes",
"=",
"$",
"field",
";",
"/*\n\t\t\t * Random stream type\n\t\t\t */",
"elseif",
"(",
"$",
"fieldId",
"==",
"10",
")",
"{",
"if",
"(",
"$",
"field",
"==",
"self",
"::",
"INT_0",
")",
"$",
"header",
"->",
"randomStream",
"=",
"self",
"::",
"RANDOMSTREAM_NONE",
";",
"elseif",
"(",
"$",
"field",
"==",
"self",
"::",
"INT_2",
")",
"$",
"header",
"->",
"randomStream",
"=",
"self",
"::",
"RANDOMSTREAM_SALSA20",
";",
"/*elseif($field == self::INT_1) // unsuported\n\t\t\t\t\t$header->randomStream= self::RANDOMSTREAM_ARC4;*/",
"}",
"}",
"$",
"header",
"->",
"headerHash",
"=",
"$",
"dreader",
"->",
"GetDigest",
"(",
")",
";",
"$",
"error",
"=",
"null",
";",
"return",
"$",
"header",
";",
"}"
]
| Parses the content of a Reader as a KdbxHeader in binary format.
@param $reader A Reader that reads the header.
@param $hashAlgo The hash algorithm to use to compute the header hash.
@param &$error A string that will receive a message in case of error.
@return A new KdbxHeader instance if it could be correctly parsed from
the reader, and null otherwise. | [
"Parses",
"the",
"content",
"of",
"a",
"Reader",
"as",
"a",
"KdbxHeader",
"in",
"binary",
"format",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/kdbxheader.php#L149-L267 | train |
shkdee/KeePassPHP | keepassphp/lib/kdbxfile.php | KdbxFile.prepareEncrypting | public function prepareEncrypting(&$error)
{
$header = $this->getHeader();
$header->masterSeed = random_bytes(self::SEED_LEN);
$header->transformSeed = random_bytes(self::SEED_LEN);
$header->encryptionIV = random_bytes(16);
$header->randomStreamKey = random_bytes(self::SEED_LEN);
$header->startBytes = random_bytes(self::STARTBYTES_LEN);
if($header->randomStream == KdbxHeader::RANDOMSTREAM_SALSA20)
{
$this->_randomStream = Salsa20Stream::create(
hash(self::HASH, $header->randomStreamKey, true),
self::SALSA20_IV);
if($this->_randomStream == null)
{
$error = "Kdbx file encrypt: random stream parameters error.";
return false;
}
}
$result = $header->toBinary(self::HASH);
if(!self::headerCheck($header))
{
$error = "Kdbx file encrypt: header check failed.";
return false;
}
$this->_headerBinary = $result;
return true;
} | php | public function prepareEncrypting(&$error)
{
$header = $this->getHeader();
$header->masterSeed = random_bytes(self::SEED_LEN);
$header->transformSeed = random_bytes(self::SEED_LEN);
$header->encryptionIV = random_bytes(16);
$header->randomStreamKey = random_bytes(self::SEED_LEN);
$header->startBytes = random_bytes(self::STARTBYTES_LEN);
if($header->randomStream == KdbxHeader::RANDOMSTREAM_SALSA20)
{
$this->_randomStream = Salsa20Stream::create(
hash(self::HASH, $header->randomStreamKey, true),
self::SALSA20_IV);
if($this->_randomStream == null)
{
$error = "Kdbx file encrypt: random stream parameters error.";
return false;
}
}
$result = $header->toBinary(self::HASH);
if(!self::headerCheck($header))
{
$error = "Kdbx file encrypt: header check failed.";
return false;
}
$this->_headerBinary = $result;
return true;
} | [
"public",
"function",
"prepareEncrypting",
"(",
"&",
"$",
"error",
")",
"{",
"$",
"header",
"=",
"$",
"this",
"->",
"getHeader",
"(",
")",
";",
"$",
"header",
"->",
"masterSeed",
"=",
"random_bytes",
"(",
"self",
"::",
"SEED_LEN",
")",
";",
"$",
"header",
"->",
"transformSeed",
"=",
"random_bytes",
"(",
"self",
"::",
"SEED_LEN",
")",
";",
"$",
"header",
"->",
"encryptionIV",
"=",
"random_bytes",
"(",
"16",
")",
";",
"$",
"header",
"->",
"randomStreamKey",
"=",
"random_bytes",
"(",
"self",
"::",
"SEED_LEN",
")",
";",
"$",
"header",
"->",
"startBytes",
"=",
"random_bytes",
"(",
"self",
"::",
"STARTBYTES_LEN",
")",
";",
"if",
"(",
"$",
"header",
"->",
"randomStream",
"==",
"KdbxHeader",
"::",
"RANDOMSTREAM_SALSA20",
")",
"{",
"$",
"this",
"->",
"_randomStream",
"=",
"Salsa20Stream",
"::",
"create",
"(",
"hash",
"(",
"self",
"::",
"HASH",
",",
"$",
"header",
"->",
"randomStreamKey",
",",
"true",
")",
",",
"self",
"::",
"SALSA20_IV",
")",
";",
"if",
"(",
"$",
"this",
"->",
"_randomStream",
"==",
"null",
")",
"{",
"$",
"error",
"=",
"\"Kdbx file encrypt: random stream parameters error.\"",
";",
"return",
"false",
";",
"}",
"}",
"$",
"result",
"=",
"$",
"header",
"->",
"toBinary",
"(",
"self",
"::",
"HASH",
")",
";",
"if",
"(",
"!",
"self",
"::",
"headerCheck",
"(",
"$",
"header",
")",
")",
"{",
"$",
"error",
"=",
"\"Kdbx file encrypt: header check failed.\"",
";",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"_headerBinary",
"=",
"$",
"result",
";",
"return",
"true",
";",
"}"
]
| Prepares the encryption of this instance by generating new random
strings for the header, serializing the header and computing its hash.
Non-random header fields must be set before calling this method.
@param &$error A string that will receive a message in case of error.
@return true if everything went well and the encrypt method can be
called, false otherwise. | [
"Prepares",
"the",
"encryption",
"of",
"this",
"instance",
"by",
"generating",
"new",
"random",
"strings",
"for",
"the",
"header",
"serializing",
"the",
"header",
"and",
"computing",
"its",
"hash",
".",
"Non",
"-",
"random",
"header",
"fields",
"must",
"be",
"set",
"before",
"calling",
"this",
"method",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/kdbxfile.php#L88-L119 | train |
shkdee/KeePassPHP | keepassphp/lib/kdbxfile.php | KdbxFile.transformKey | private static function transformKey(iKey $key, KdbxHeader $header)
{
$keyHash = $key->getHash();
$cipher = Cipher::Create('aes-256-ecb', $header->transformSeed,
"", Cipher::PADDING_NONE);
if($cipher == null)
return null;
// We have to do $rounds encryptions, where $rounds is a 64 bit
// unsigned integer. Since PHP does not handle 64 bit integers in a
// clear way, nor 32 bit unsigned integers, it is safer to take
// $rounds as an array of 4 short (16 bit) unsigned integers.
// Remember that $rounds is encoded in little-endian.
$rounds = array_values(unpack("v4", $header->rounds));
// To go even faster, represent $rounds in base 2**30 by only three
// signed integers, that PHP should handle correctly. $o, $t and $h
// will respectively be ones, tens and hundrers. $o and $t each take 30
// bits, $h takes the remaining 4.
$o = $rounds[0] | (($rounds[1] & 0x3fff) << 16);
$t = (($rounds[1] & 0xc000) >> 14) | ($rounds[2] << 2) |
(($rounds[3] & 0x0fff) << 18);
$h = ($rounds[3] & 0xf000) >> 12;
// So virtually, the number of rounds is $o + ($t << 30) + ($h << 60).
$loop = false;
do
{
// Let's do a direct, very fast loop on the ones $o
if($o > 0)
$keyHash = $cipher->encryptManyTimes($keyHash, $o);
// whether there is still some rounds to perform
$loop = false;
// then, remove 1 from the number of rounds (that's just a
// substraction in base 2**30 of a 3-digit number), knowing that
// $o equals 0.
if($t > 0)
{
$t--;
// We set $o to (2**30 - 1) + 1 = 2**30 because we still
// have to do the encryption round that we're currently
// substracting. So we don't really do a substraction, we
// just write the number differently. That's also why we
// chose to represent $rounds in base 2**30 rather than 2**31.
$o = 0x40000000;
$loop = true;
}
else if($h > 0)
{
$h--;
$t = 0x3fffffff;
// same as above
$o = 0x40000000;
$loop = true;
}
} while($loop);
$finalKey = hash(self::HASH, $keyHash, true);
return hash(self::HASH, $header->masterSeed . $finalKey, true);
} | php | private static function transformKey(iKey $key, KdbxHeader $header)
{
$keyHash = $key->getHash();
$cipher = Cipher::Create('aes-256-ecb', $header->transformSeed,
"", Cipher::PADDING_NONE);
if($cipher == null)
return null;
// We have to do $rounds encryptions, where $rounds is a 64 bit
// unsigned integer. Since PHP does not handle 64 bit integers in a
// clear way, nor 32 bit unsigned integers, it is safer to take
// $rounds as an array of 4 short (16 bit) unsigned integers.
// Remember that $rounds is encoded in little-endian.
$rounds = array_values(unpack("v4", $header->rounds));
// To go even faster, represent $rounds in base 2**30 by only three
// signed integers, that PHP should handle correctly. $o, $t and $h
// will respectively be ones, tens and hundrers. $o and $t each take 30
// bits, $h takes the remaining 4.
$o = $rounds[0] | (($rounds[1] & 0x3fff) << 16);
$t = (($rounds[1] & 0xc000) >> 14) | ($rounds[2] << 2) |
(($rounds[3] & 0x0fff) << 18);
$h = ($rounds[3] & 0xf000) >> 12;
// So virtually, the number of rounds is $o + ($t << 30) + ($h << 60).
$loop = false;
do
{
// Let's do a direct, very fast loop on the ones $o
if($o > 0)
$keyHash = $cipher->encryptManyTimes($keyHash, $o);
// whether there is still some rounds to perform
$loop = false;
// then, remove 1 from the number of rounds (that's just a
// substraction in base 2**30 of a 3-digit number), knowing that
// $o equals 0.
if($t > 0)
{
$t--;
// We set $o to (2**30 - 1) + 1 = 2**30 because we still
// have to do the encryption round that we're currently
// substracting. So we don't really do a substraction, we
// just write the number differently. That's also why we
// chose to represent $rounds in base 2**30 rather than 2**31.
$o = 0x40000000;
$loop = true;
}
else if($h > 0)
{
$h--;
$t = 0x3fffffff;
// same as above
$o = 0x40000000;
$loop = true;
}
} while($loop);
$finalKey = hash(self::HASH, $keyHash, true);
return hash(self::HASH, $header->masterSeed . $finalKey, true);
} | [
"private",
"static",
"function",
"transformKey",
"(",
"iKey",
"$",
"key",
",",
"KdbxHeader",
"$",
"header",
")",
"{",
"$",
"keyHash",
"=",
"$",
"key",
"->",
"getHash",
"(",
")",
";",
"$",
"cipher",
"=",
"Cipher",
"::",
"Create",
"(",
"'aes-256-ecb'",
",",
"$",
"header",
"->",
"transformSeed",
",",
"\"\"",
",",
"Cipher",
"::",
"PADDING_NONE",
")",
";",
"if",
"(",
"$",
"cipher",
"==",
"null",
")",
"return",
"null",
";",
"// We have to do $rounds encryptions, where $rounds is a 64 bit",
"// unsigned integer. Since PHP does not handle 64 bit integers in a",
"// clear way, nor 32 bit unsigned integers, it is safer to take",
"// $rounds as an array of 4 short (16 bit) unsigned integers.",
"// Remember that $rounds is encoded in little-endian.",
"$",
"rounds",
"=",
"array_values",
"(",
"unpack",
"(",
"\"v4\"",
",",
"$",
"header",
"->",
"rounds",
")",
")",
";",
"// To go even faster, represent $rounds in base 2**30 by only three",
"// signed integers, that PHP should handle correctly. $o, $t and $h",
"// will respectively be ones, tens and hundrers. $o and $t each take 30",
"// bits, $h takes the remaining 4.",
"$",
"o",
"=",
"$",
"rounds",
"[",
"0",
"]",
"|",
"(",
"(",
"$",
"rounds",
"[",
"1",
"]",
"&",
"0x3fff",
")",
"<<",
"16",
")",
";",
"$",
"t",
"=",
"(",
"(",
"$",
"rounds",
"[",
"1",
"]",
"&",
"0xc000",
")",
">>",
"14",
")",
"|",
"(",
"$",
"rounds",
"[",
"2",
"]",
"<<",
"2",
")",
"|",
"(",
"(",
"$",
"rounds",
"[",
"3",
"]",
"&",
"0x0fff",
")",
"<<",
"18",
")",
";",
"$",
"h",
"=",
"(",
"$",
"rounds",
"[",
"3",
"]",
"&",
"0xf000",
")",
">>",
"12",
";",
"// So virtually, the number of rounds is $o + ($t << 30) + ($h << 60).",
"$",
"loop",
"=",
"false",
";",
"do",
"{",
"// Let's do a direct, very fast loop on the ones $o",
"if",
"(",
"$",
"o",
">",
"0",
")",
"$",
"keyHash",
"=",
"$",
"cipher",
"->",
"encryptManyTimes",
"(",
"$",
"keyHash",
",",
"$",
"o",
")",
";",
"// whether there is still some rounds to perform",
"$",
"loop",
"=",
"false",
";",
"// then, remove 1 from the number of rounds (that's just a",
"// substraction in base 2**30 of a 3-digit number), knowing that",
"// $o equals 0.",
"if",
"(",
"$",
"t",
">",
"0",
")",
"{",
"$",
"t",
"--",
";",
"// We set $o to (2**30 - 1) + 1 = 2**30 because we still",
"// have to do the encryption round that we're currently",
"// substracting. So we don't really do a substraction, we",
"// just write the number differently. That's also why we",
"// chose to represent $rounds in base 2**30 rather than 2**31.",
"$",
"o",
"=",
"0x40000000",
";",
"$",
"loop",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"$",
"h",
">",
"0",
")",
"{",
"$",
"h",
"--",
";",
"$",
"t",
"=",
"0x3fffffff",
";",
"// same as above",
"$",
"o",
"=",
"0x40000000",
";",
"$",
"loop",
"=",
"true",
";",
"}",
"}",
"while",
"(",
"$",
"loop",
")",
";",
"$",
"finalKey",
"=",
"hash",
"(",
"self",
"::",
"HASH",
",",
"$",
"keyHash",
",",
"true",
")",
";",
"return",
"hash",
"(",
"self",
"::",
"HASH",
",",
"$",
"header",
"->",
"masterSeed",
".",
"$",
"finalKey",
",",
"true",
")",
";",
"}"
]
| Computes the AES encryption key of a Kdbx file from its keys and header.
@param $key The encryption key.
@param $header The Kdbx file header.
@return A 32-byte-long string that can be used as an AES key, or null
if no suitable cryptography extension is laoded. | [
"Computes",
"the",
"AES",
"encryption",
"key",
"of",
"a",
"Kdbx",
"file",
"from",
"its",
"keys",
"and",
"header",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/kdbxfile.php#L305-L361 | train |
shkdee/KeePassPHP | keepassphp/lib/key.php | CompositeKey.getHash | public function getHash()
{
$h = hash_init($this->_hashAlgo);
foreach($this->_keys as &$v)
hash_update($h, $v);
$r = hash_final($h, true);
unset($h);
return $r;
} | php | public function getHash()
{
$h = hash_init($this->_hashAlgo);
foreach($this->_keys as &$v)
hash_update($h, $v);
$r = hash_final($h, true);
unset($h);
return $r;
} | [
"public",
"function",
"getHash",
"(",
")",
"{",
"$",
"h",
"=",
"hash_init",
"(",
"$",
"this",
"->",
"_hashAlgo",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"_keys",
"as",
"&",
"$",
"v",
")",
"hash_update",
"(",
"$",
"h",
",",
"$",
"v",
")",
";",
"$",
"r",
"=",
"hash_final",
"(",
"$",
"h",
",",
"true",
")",
";",
"unset",
"(",
"$",
"h",
")",
";",
"return",
"$",
"r",
";",
"}"
]
| Computes the hash of all the keys of this CompositeKey.
@return A raw hash string. | [
"Computes",
"the",
"hash",
"of",
"all",
"the",
"keys",
"of",
"this",
"CompositeKey",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/key.php#L60-L68 | train |
shkdee/KeePassPHP | keepassphp/lib/entry.php | Entry.getStringField | function getStringField($key)
{
return isset($this->stringFields[$key])
? $this->stringFields[$key]->getPlainString()
: "";
} | php | function getStringField($key)
{
return isset($this->stringFields[$key])
? $this->stringFields[$key]->getPlainString()
: "";
} | [
"function",
"getStringField",
"(",
"$",
"key",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"stringFields",
"[",
"$",
"key",
"]",
")",
"?",
"$",
"this",
"->",
"stringFields",
"[",
"$",
"key",
"]",
"->",
"getPlainString",
"(",
")",
":",
"\"\"",
";",
"}"
]
| Gets the string value of this Entry string field corresponding to the
given key, or an empty string of no field with that key exists.
@param $key A key.
@return A non-null string, containing the value of the field. | [
"Gets",
"the",
"string",
"value",
"of",
"this",
"Entry",
"string",
"field",
"corresponding",
"to",
"the",
"given",
"key",
"or",
"an",
"empty",
"string",
"of",
"no",
"field",
"with",
"that",
"key",
"exists",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/entry.php#L65-L70 | train |
shkdee/KeePassPHP | keepassphp/lib/entry.php | Entry.addHistoryEntry | private function addHistoryEntry($entry)
{
if($entry != null)
{
if($this->history == null)
$this->history = array();
$this->history[] = $entry;
}
} | php | private function addHistoryEntry($entry)
{
if($entry != null)
{
if($this->history == null)
$this->history = array();
$this->history[] = $entry;
}
} | [
"private",
"function",
"addHistoryEntry",
"(",
"$",
"entry",
")",
"{",
"if",
"(",
"$",
"entry",
"!=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"history",
"==",
"null",
")",
"$",
"this",
"->",
"history",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"history",
"[",
"]",
"=",
"$",
"entry",
";",
"}",
"}"
]
| Adds an Entry instance to the history of this entry.
@param $entry An Entry instance, possibly null (it is then ignored). | [
"Adds",
"an",
"Entry",
"instance",
"to",
"the",
"history",
"of",
"this",
"entry",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/entry.php#L76-L84 | train |
shkdee/KeePassPHP | keepassphp/lib/entry.php | Entry.readString | private function readString(ProtectedXMLReader $reader)
{
$d = $reader->depth();
$key = null;
$value = null;
while($reader->read($d))
{
if($reader->isElement(Database::XML_STRING_KEY))
$key = $reader->readTextInside();
elseif($reader->isElement(Database::XML_STRING_VALUE))
$value = $reader->readTextInside(true);
}
if(empty($key) || $value == null)
return;
if(\strcasecmp($key, Database::KEY_PASSWORD) == 0)
$this->password = $value;
else
$this->stringFields[$key] = $value;
} | php | private function readString(ProtectedXMLReader $reader)
{
$d = $reader->depth();
$key = null;
$value = null;
while($reader->read($d))
{
if($reader->isElement(Database::XML_STRING_KEY))
$key = $reader->readTextInside();
elseif($reader->isElement(Database::XML_STRING_VALUE))
$value = $reader->readTextInside(true);
}
if(empty($key) || $value == null)
return;
if(\strcasecmp($key, Database::KEY_PASSWORD) == 0)
$this->password = $value;
else
$this->stringFields[$key] = $value;
} | [
"private",
"function",
"readString",
"(",
"ProtectedXMLReader",
"$",
"reader",
")",
"{",
"$",
"d",
"=",
"$",
"reader",
"->",
"depth",
"(",
")",
";",
"$",
"key",
"=",
"null",
";",
"$",
"value",
"=",
"null",
";",
"while",
"(",
"$",
"reader",
"->",
"read",
"(",
"$",
"d",
")",
")",
"{",
"if",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_STRING_KEY",
")",
")",
"$",
"key",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_STRING_VALUE",
")",
")",
"$",
"value",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
"true",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"key",
")",
"||",
"$",
"value",
"==",
"null",
")",
"return",
";",
"if",
"(",
"\\",
"strcasecmp",
"(",
"$",
"key",
",",
"Database",
"::",
"KEY_PASSWORD",
")",
"==",
"0",
")",
"$",
"this",
"->",
"password",
"=",
"$",
"value",
";",
"else",
"$",
"this",
"->",
"stringFields",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}"
]
| Parses a string XML element node.
@param $reader A XML reader located at a string element node. | [
"Parses",
"a",
"string",
"XML",
"element",
"node",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/entry.php#L90-L108 | train |
shkdee/KeePassPHP | keepassphp/lib/entry.php | Entry.loadFromXML | public static function loadFromXML(ProtectedXMLReader $reader)
{
if($reader == null)
return null;
$entry = new Entry();
$d = $reader->depth();
while($reader->read($d))
{
if($reader->isElement(Database::XML_UUID))
$entry->uuid = $reader->readTextInside();
elseif($reader->isElement(Database::XML_ICONID))
$entry->icon = $reader->readTextInside();
elseif($reader->isElement(Database::XML_CUSTOMICONUUID))
$entry->customIcon = $reader->readTextInside();
else if($reader->isElement(Database::XML_TAGS))
$entry->tags = $reader->readTextInside();
elseif($reader->isElement(Database::XML_STRING))
$entry->readString($reader);
elseif($reader->isElement(Database::XML_HISTORY))
{
$historyD = $reader->depth();
while($reader->read($historyD))
{
if($reader->isElement(Database::XML_ENTRY))
$entry->addHistoryEntry(self::loadFromXML($reader));
}
}
}
return $entry;
} | php | public static function loadFromXML(ProtectedXMLReader $reader)
{
if($reader == null)
return null;
$entry = new Entry();
$d = $reader->depth();
while($reader->read($d))
{
if($reader->isElement(Database::XML_UUID))
$entry->uuid = $reader->readTextInside();
elseif($reader->isElement(Database::XML_ICONID))
$entry->icon = $reader->readTextInside();
elseif($reader->isElement(Database::XML_CUSTOMICONUUID))
$entry->customIcon = $reader->readTextInside();
else if($reader->isElement(Database::XML_TAGS))
$entry->tags = $reader->readTextInside();
elseif($reader->isElement(Database::XML_STRING))
$entry->readString($reader);
elseif($reader->isElement(Database::XML_HISTORY))
{
$historyD = $reader->depth();
while($reader->read($historyD))
{
if($reader->isElement(Database::XML_ENTRY))
$entry->addHistoryEntry(self::loadFromXML($reader));
}
}
}
return $entry;
} | [
"public",
"static",
"function",
"loadFromXML",
"(",
"ProtectedXMLReader",
"$",
"reader",
")",
"{",
"if",
"(",
"$",
"reader",
"==",
"null",
")",
"return",
"null",
";",
"$",
"entry",
"=",
"new",
"Entry",
"(",
")",
";",
"$",
"d",
"=",
"$",
"reader",
"->",
"depth",
"(",
")",
";",
"while",
"(",
"$",
"reader",
"->",
"read",
"(",
"$",
"d",
")",
")",
"{",
"if",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_UUID",
")",
")",
"$",
"entry",
"->",
"uuid",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_ICONID",
")",
")",
"$",
"entry",
"->",
"icon",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_CUSTOMICONUUID",
")",
")",
"$",
"entry",
"->",
"customIcon",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
";",
"else",
"if",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_TAGS",
")",
")",
"$",
"entry",
"->",
"tags",
"=",
"$",
"reader",
"->",
"readTextInside",
"(",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_STRING",
")",
")",
"$",
"entry",
"->",
"readString",
"(",
"$",
"reader",
")",
";",
"elseif",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_HISTORY",
")",
")",
"{",
"$",
"historyD",
"=",
"$",
"reader",
"->",
"depth",
"(",
")",
";",
"while",
"(",
"$",
"reader",
"->",
"read",
"(",
"$",
"historyD",
")",
")",
"{",
"if",
"(",
"$",
"reader",
"->",
"isElement",
"(",
"Database",
"::",
"XML_ENTRY",
")",
")",
"$",
"entry",
"->",
"addHistoryEntry",
"(",
"self",
"::",
"loadFromXML",
"(",
"$",
"reader",
")",
")",
";",
"}",
"}",
"}",
"return",
"$",
"entry",
";",
"}"
]
| Creates a new Entry instance from a ProtectedXMLReader instance reading
a KeePass 2.x database and located at an Entry element node.
@param $reader A XML reader.
@return A Entry instance if the parsing went okay, null otherwise. | [
"Creates",
"a",
"new",
"Entry",
"instance",
"from",
"a",
"ProtectedXMLReader",
"instance",
"reading",
"a",
"KeePass",
"2",
".",
"x",
"database",
"and",
"located",
"at",
"an",
"Entry",
"element",
"node",
"."
]
| ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03 | https://github.com/shkdee/KeePassPHP/blob/ff9a00ad1d9f921afa6c831a72b10a0fb16dfc03/keepassphp/lib/entry.php#L206-L235 | train |
TheDMSGroup/mautic-extended-field | Model/OverrideListModel.php | OverrideListModel.getChoiceFields | public function getChoiceFields()
{
$choices = parent::getChoiceFields();
// Shift all extended fields into the "lead" object.
$resort = false;
foreach (['extendedField', 'extendedFieldSecure'] as $key) {
if (isset($choices[$key])) {
foreach ($choices[$key] as $fieldAlias => $field) {
$choices['lead'][$fieldAlias] = $field;
unset($choices[$key][$fieldAlias]);
}
unset($choices[$key]);
$resort = true;
}
}
// Sort after we included extended fields (same as core).
if ($resort) {
foreach ($choices as $key => $choice) {
$cmp = function ($a, $b) {
return strcmp($a['label'], $b['label']);
};
uasort($choice, $cmp);
$choices[$key] = $choice;
}
}
return $choices;
} | php | public function getChoiceFields()
{
$choices = parent::getChoiceFields();
// Shift all extended fields into the "lead" object.
$resort = false;
foreach (['extendedField', 'extendedFieldSecure'] as $key) {
if (isset($choices[$key])) {
foreach ($choices[$key] as $fieldAlias => $field) {
$choices['lead'][$fieldAlias] = $field;
unset($choices[$key][$fieldAlias]);
}
unset($choices[$key]);
$resort = true;
}
}
// Sort after we included extended fields (same as core).
if ($resort) {
foreach ($choices as $key => $choice) {
$cmp = function ($a, $b) {
return strcmp($a['label'], $b['label']);
};
uasort($choice, $cmp);
$choices[$key] = $choice;
}
}
return $choices;
} | [
"public",
"function",
"getChoiceFields",
"(",
")",
"{",
"$",
"choices",
"=",
"parent",
"::",
"getChoiceFields",
"(",
")",
";",
"// Shift all extended fields into the \"lead\" object.",
"$",
"resort",
"=",
"false",
";",
"foreach",
"(",
"[",
"'extendedField'",
",",
"'extendedFieldSecure'",
"]",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"choices",
"[",
"$",
"key",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"choices",
"[",
"$",
"key",
"]",
"as",
"$",
"fieldAlias",
"=>",
"$",
"field",
")",
"{",
"$",
"choices",
"[",
"'lead'",
"]",
"[",
"$",
"fieldAlias",
"]",
"=",
"$",
"field",
";",
"unset",
"(",
"$",
"choices",
"[",
"$",
"key",
"]",
"[",
"$",
"fieldAlias",
"]",
")",
";",
"}",
"unset",
"(",
"$",
"choices",
"[",
"$",
"key",
"]",
")",
";",
"$",
"resort",
"=",
"true",
";",
"}",
"}",
"// Sort after we included extended fields (same as core).",
"if",
"(",
"$",
"resort",
")",
"{",
"foreach",
"(",
"$",
"choices",
"as",
"$",
"key",
"=>",
"$",
"choice",
")",
"{",
"$",
"cmp",
"=",
"function",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"return",
"strcmp",
"(",
"$",
"a",
"[",
"'label'",
"]",
",",
"$",
"b",
"[",
"'label'",
"]",
")",
";",
"}",
";",
"uasort",
"(",
"$",
"choice",
",",
"$",
"cmp",
")",
";",
"$",
"choices",
"[",
"$",
"key",
"]",
"=",
"$",
"choice",
";",
"}",
"}",
"return",
"$",
"choices",
";",
"}"
]
| Get a list of field choices for filters.
Alterations to core:
Form validation to support extended fields.
@return array | [
"Get",
"a",
"list",
"of",
"field",
"choices",
"for",
"filters",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/Model/OverrideListModel.php#L29-L57 | train |
TheDMSGroup/mautic-extended-field | EventListener/LeadSubscriber.php | LeadSubscriber.correctExtendedFieldColumns | public function correctExtendedFieldColumns(LeadListQueryBuilderGeneratedEvent $event)
{
$q = $event->getQueryBuilder();
$parts = $q->getQueryParts();
$changedParts = [];
$aliases = [];
if (isset($parts['join']['l']) && !empty($this->aliases)) {
// Confirm the aliases are for the current query by present joins.
foreach ($parts['join']['l'] as $key => $join) {
if (
is_array($join)
&& isset($join['joinType'])
&& 'left' === $join['joinType']
&& isset($this->aliases[$join['joinAlias']])
) {
$aliases[$join['joinAlias']] = $this->aliases[$join['joinAlias']];
}
}
if (count($aliases)) {
foreach ($aliases as $joinAlias => $fieldAlias) {
foreach (['where', 'orWhere', 'andWhere', 'having', 'orHaving', 'andHaving'] as $type) {
if (isset($parts[$type])) {
$changedParts[$type] = $this->partCorrect($parts[$type], $fieldAlias, $this->seen[$fieldAlias]);
}
}
}
}
foreach ($changedParts as $type => $t) {
$q->setQueryPart($type, $parts[$type]);
}
}
} | php | public function correctExtendedFieldColumns(LeadListQueryBuilderGeneratedEvent $event)
{
$q = $event->getQueryBuilder();
$parts = $q->getQueryParts();
$changedParts = [];
$aliases = [];
if (isset($parts['join']['l']) && !empty($this->aliases)) {
// Confirm the aliases are for the current query by present joins.
foreach ($parts['join']['l'] as $key => $join) {
if (
is_array($join)
&& isset($join['joinType'])
&& 'left' === $join['joinType']
&& isset($this->aliases[$join['joinAlias']])
) {
$aliases[$join['joinAlias']] = $this->aliases[$join['joinAlias']];
}
}
if (count($aliases)) {
foreach ($aliases as $joinAlias => $fieldAlias) {
foreach (['where', 'orWhere', 'andWhere', 'having', 'orHaving', 'andHaving'] as $type) {
if (isset($parts[$type])) {
$changedParts[$type] = $this->partCorrect($parts[$type], $fieldAlias, $this->seen[$fieldAlias]);
}
}
}
}
foreach ($changedParts as $type => $t) {
$q->setQueryPart($type, $parts[$type]);
}
}
} | [
"public",
"function",
"correctExtendedFieldColumns",
"(",
"LeadListQueryBuilderGeneratedEvent",
"$",
"event",
")",
"{",
"$",
"q",
"=",
"$",
"event",
"->",
"getQueryBuilder",
"(",
")",
";",
"$",
"parts",
"=",
"$",
"q",
"->",
"getQueryParts",
"(",
")",
";",
"$",
"changedParts",
"=",
"[",
"]",
";",
"$",
"aliases",
"=",
"[",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"parts",
"[",
"'join'",
"]",
"[",
"'l'",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"this",
"->",
"aliases",
")",
")",
"{",
"// Confirm the aliases are for the current query by present joins.",
"foreach",
"(",
"$",
"parts",
"[",
"'join'",
"]",
"[",
"'l'",
"]",
"as",
"$",
"key",
"=>",
"$",
"join",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"join",
")",
"&&",
"isset",
"(",
"$",
"join",
"[",
"'joinType'",
"]",
")",
"&&",
"'left'",
"===",
"$",
"join",
"[",
"'joinType'",
"]",
"&&",
"isset",
"(",
"$",
"this",
"->",
"aliases",
"[",
"$",
"join",
"[",
"'joinAlias'",
"]",
"]",
")",
")",
"{",
"$",
"aliases",
"[",
"$",
"join",
"[",
"'joinAlias'",
"]",
"]",
"=",
"$",
"this",
"->",
"aliases",
"[",
"$",
"join",
"[",
"'joinAlias'",
"]",
"]",
";",
"}",
"}",
"if",
"(",
"count",
"(",
"$",
"aliases",
")",
")",
"{",
"foreach",
"(",
"$",
"aliases",
"as",
"$",
"joinAlias",
"=>",
"$",
"fieldAlias",
")",
"{",
"foreach",
"(",
"[",
"'where'",
",",
"'orWhere'",
",",
"'andWhere'",
",",
"'having'",
",",
"'orHaving'",
",",
"'andHaving'",
"]",
"as",
"$",
"type",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"parts",
"[",
"$",
"type",
"]",
")",
")",
"{",
"$",
"changedParts",
"[",
"$",
"type",
"]",
"=",
"$",
"this",
"->",
"partCorrect",
"(",
"$",
"parts",
"[",
"$",
"type",
"]",
",",
"$",
"fieldAlias",
",",
"$",
"this",
"->",
"seen",
"[",
"$",
"fieldAlias",
"]",
")",
";",
"}",
"}",
"}",
"}",
"foreach",
"(",
"$",
"changedParts",
"as",
"$",
"type",
"=>",
"$",
"t",
")",
"{",
"$",
"q",
"->",
"setQueryPart",
"(",
"$",
"type",
",",
"$",
"parts",
"[",
"$",
"type",
"]",
")",
";",
"}",
"}",
"}"
]
| After addExtendedFieldFilters, and the query is fully built, we must correct extended fields to use
the correct table aliases instead of "l.".
@param LeadListQueryBuilderGeneratedEvent $event | [
"After",
"addExtendedFieldFilters",
"and",
"the",
"query",
"is",
"fully",
"built",
"we",
"must",
"correct",
"extended",
"fields",
"to",
"use",
"the",
"correct",
"table",
"aliases",
"instead",
"of",
"l",
".",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/EventListener/LeadSubscriber.php#L107-L138 | train |
Oefenweb/php-statistics | src/Statistics.php | Statistics.frequency | public static function frequency($values)
{
$frequency = [];
foreach ($values as $value) {
// Floats cannot be indices
if (is_float($value)) {
$value = strval($value);
}
if (!isset($frequency[$value])) {
$frequency[$value] = 1;
} else {
$frequency[$value] += 1;
}
}
asort($frequency);
return $frequency;
} | php | public static function frequency($values)
{
$frequency = [];
foreach ($values as $value) {
// Floats cannot be indices
if (is_float($value)) {
$value = strval($value);
}
if (!isset($frequency[$value])) {
$frequency[$value] = 1;
} else {
$frequency[$value] += 1;
}
}
asort($frequency);
return $frequency;
} | [
"public",
"static",
"function",
"frequency",
"(",
"$",
"values",
")",
"{",
"$",
"frequency",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"value",
")",
"{",
"// Floats cannot be indices",
"if",
"(",
"is_float",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"strval",
"(",
"$",
"value",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"frequency",
"[",
"$",
"value",
"]",
")",
")",
"{",
"$",
"frequency",
"[",
"$",
"value",
"]",
"=",
"1",
";",
"}",
"else",
"{",
"$",
"frequency",
"[",
"$",
"value",
"]",
"+=",
"1",
";",
"}",
"}",
"asort",
"(",
"$",
"frequency",
")",
";",
"return",
"$",
"frequency",
";",
"}"
]
| Calculates the frequency table for a given set of values.
@param array $values The input values
@return array The frequency table | [
"Calculates",
"the",
"frequency",
"table",
"for",
"a",
"given",
"set",
"of",
"values",
"."
]
| 7014d03ccba1351e620046fc0ea95d3d5db57984 | https://github.com/Oefenweb/php-statistics/blob/7014d03ccba1351e620046fc0ea95d3d5db57984/src/Statistics.php#L65-L84 | train |
Oefenweb/php-statistics | src/Statistics.php | Statistics.mode | public static function mode($values)
{
$frequency = self::frequency($values);
if (count($frequency) === 1) {
return key($frequency);
}
$lastTwo = array_slice($frequency, -2, 2, true);
$firstFrequency = current($lastTwo);
$lastFrequency = next($lastTwo);
if ($firstFrequency !== $lastFrequency) {
return key($lastTwo);
}
throw new StatisticsError('There is not exactly one most common value.');
} | php | public static function mode($values)
{
$frequency = self::frequency($values);
if (count($frequency) === 1) {
return key($frequency);
}
$lastTwo = array_slice($frequency, -2, 2, true);
$firstFrequency = current($lastTwo);
$lastFrequency = next($lastTwo);
if ($firstFrequency !== $lastFrequency) {
return key($lastTwo);
}
throw new StatisticsError('There is not exactly one most common value.');
} | [
"public",
"static",
"function",
"mode",
"(",
"$",
"values",
")",
"{",
"$",
"frequency",
"=",
"self",
"::",
"frequency",
"(",
"$",
"values",
")",
";",
"if",
"(",
"count",
"(",
"$",
"frequency",
")",
"===",
"1",
")",
"{",
"return",
"key",
"(",
"$",
"frequency",
")",
";",
"}",
"$",
"lastTwo",
"=",
"array_slice",
"(",
"$",
"frequency",
",",
"-",
"2",
",",
"2",
",",
"true",
")",
";",
"$",
"firstFrequency",
"=",
"current",
"(",
"$",
"lastTwo",
")",
";",
"$",
"lastFrequency",
"=",
"next",
"(",
"$",
"lastTwo",
")",
";",
"if",
"(",
"$",
"firstFrequency",
"!==",
"$",
"lastFrequency",
")",
"{",
"return",
"key",
"(",
"$",
"lastTwo",
")",
";",
"}",
"throw",
"new",
"StatisticsError",
"(",
"'There is not exactly one most common value.'",
")",
";",
"}"
]
| Calculates the mode for a given set of values.
@param array $values The input values
@return float|int The mode of values as an integer or float
@throws \Oefenweb\Statistics\StatisticsError | [
"Calculates",
"the",
"mode",
"for",
"a",
"given",
"set",
"of",
"values",
"."
]
| 7014d03ccba1351e620046fc0ea95d3d5db57984 | https://github.com/Oefenweb/php-statistics/blob/7014d03ccba1351e620046fc0ea95d3d5db57984/src/Statistics.php#L93-L110 | train |
Oefenweb/php-statistics | src/Statistics.php | Statistics.variance | public static function variance($values, $sample = true)
{
$numberOfValues = count($values);
$mean = self::mean($values);
$squaredDifferences = [];
foreach ($values as $value) {
$squaredDifferences[] = self::squaredDifference($value, $mean);
}
$sumOfSquaredDifferences = self::sum($squaredDifferences);
if ($sample) {
$variance = $sumOfSquaredDifferences / ($numberOfValues - 1);
} else {
$variance = $sumOfSquaredDifferences / $numberOfValues;
}
return $variance;
} | php | public static function variance($values, $sample = true)
{
$numberOfValues = count($values);
$mean = self::mean($values);
$squaredDifferences = [];
foreach ($values as $value) {
$squaredDifferences[] = self::squaredDifference($value, $mean);
}
$sumOfSquaredDifferences = self::sum($squaredDifferences);
if ($sample) {
$variance = $sumOfSquaredDifferences / ($numberOfValues - 1);
} else {
$variance = $sumOfSquaredDifferences / $numberOfValues;
}
return $variance;
} | [
"public",
"static",
"function",
"variance",
"(",
"$",
"values",
",",
"$",
"sample",
"=",
"true",
")",
"{",
"$",
"numberOfValues",
"=",
"count",
"(",
"$",
"values",
")",
";",
"$",
"mean",
"=",
"self",
"::",
"mean",
"(",
"$",
"values",
")",
";",
"$",
"squaredDifferences",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"value",
")",
"{",
"$",
"squaredDifferences",
"[",
"]",
"=",
"self",
"::",
"squaredDifference",
"(",
"$",
"value",
",",
"$",
"mean",
")",
";",
"}",
"$",
"sumOfSquaredDifferences",
"=",
"self",
"::",
"sum",
"(",
"$",
"squaredDifferences",
")",
";",
"if",
"(",
"$",
"sample",
")",
"{",
"$",
"variance",
"=",
"$",
"sumOfSquaredDifferences",
"/",
"(",
"$",
"numberOfValues",
"-",
"1",
")",
";",
"}",
"else",
"{",
"$",
"variance",
"=",
"$",
"sumOfSquaredDifferences",
"/",
"$",
"numberOfValues",
";",
"}",
"return",
"$",
"variance",
";",
"}"
]
| Calculates the variance for a given set of values.
@param array $values The input values
@param bool $sample Whether or not to compensate for small samples (n - 1), defaults to true
@return float|int The variance of values as an integer or float | [
"Calculates",
"the",
"variance",
"for",
"a",
"given",
"set",
"of",
"values",
"."
]
| 7014d03ccba1351e620046fc0ea95d3d5db57984 | https://github.com/Oefenweb/php-statistics/blob/7014d03ccba1351e620046fc0ea95d3d5db57984/src/Statistics.php#L131-L149 | train |
TheDMSGroup/mautic-extended-field | EventListener/ReportSubscriber.php | ReportSubscriber.convertToExtendedFieldQuery | private function convertToExtendedFieldQuery()
{
$this->fieldModel = $this->dispatcher->getContainer()->get('mautic.lead.model.field');
$this->selectParts = $this->query->getQueryPart('select');
$this->orderByParts = $this->query->getQueryPart('orderBy');
$this->groupByParts = $this->query->getQueryPart('groupBy');
$this->filters = $this->event->getReport()->getFilters();
$this->where = $this->query->getQueryPart('where');
$this->fieldTables = isset($this->fieldTables) ? $this->fieldTables : [];
$this->count = 0;
if (!$this->extendedFields) {
// Previous method deprecated:
// $fields = $this->fieldModel->getEntities(
// [
// [
// 'column' => 'f.isPublished',
// 'expr' => 'eq',
// 'value' => true,
// ],
// 'force' => [
// 'column' => 'f.object',
// 'expr' => 'in',
// 'value' => ['extendedField', 'extendedFieldSecure'],
// ],
// 'hydration_mode' => 'HYDRATE_ARRAY',
// ]
// );
// // Key by alias.
// foreach ($fields as $field) {
// $this->extendedFields[$field['alias']] = $field;
// }
$this->extendedFields = $this->fieldModel->getExtendedFields();
}
$this->alterSelect();
if (method_exists($this->event, 'getQuery')) { // identify ReportQueryEvent instance in backwards compatible way
$this->alterOrderBy();
}
$this->alterGroupBy();
$this->alterWhere();
$this->query->select($this->selectParts);
if (method_exists($this->event, 'getQuery') && !empty($this->orderByParts)) {
$orderBy = implode(',', $this->orderByParts);
$this->query->add('orderBy', $orderBy);
}
if (!empty($this->groupByParts)) {
$this->query->groupBy($this->groupByParts);
}
if (!empty($this->where)) {
$this->query->where($this->where);
}
} | php | private function convertToExtendedFieldQuery()
{
$this->fieldModel = $this->dispatcher->getContainer()->get('mautic.lead.model.field');
$this->selectParts = $this->query->getQueryPart('select');
$this->orderByParts = $this->query->getQueryPart('orderBy');
$this->groupByParts = $this->query->getQueryPart('groupBy');
$this->filters = $this->event->getReport()->getFilters();
$this->where = $this->query->getQueryPart('where');
$this->fieldTables = isset($this->fieldTables) ? $this->fieldTables : [];
$this->count = 0;
if (!$this->extendedFields) {
// Previous method deprecated:
// $fields = $this->fieldModel->getEntities(
// [
// [
// 'column' => 'f.isPublished',
// 'expr' => 'eq',
// 'value' => true,
// ],
// 'force' => [
// 'column' => 'f.object',
// 'expr' => 'in',
// 'value' => ['extendedField', 'extendedFieldSecure'],
// ],
// 'hydration_mode' => 'HYDRATE_ARRAY',
// ]
// );
// // Key by alias.
// foreach ($fields as $field) {
// $this->extendedFields[$field['alias']] = $field;
// }
$this->extendedFields = $this->fieldModel->getExtendedFields();
}
$this->alterSelect();
if (method_exists($this->event, 'getQuery')) { // identify ReportQueryEvent instance in backwards compatible way
$this->alterOrderBy();
}
$this->alterGroupBy();
$this->alterWhere();
$this->query->select($this->selectParts);
if (method_exists($this->event, 'getQuery') && !empty($this->orderByParts)) {
$orderBy = implode(',', $this->orderByParts);
$this->query->add('orderBy', $orderBy);
}
if (!empty($this->groupByParts)) {
$this->query->groupBy($this->groupByParts);
}
if (!empty($this->where)) {
$this->query->where($this->where);
}
} | [
"private",
"function",
"convertToExtendedFieldQuery",
"(",
")",
"{",
"$",
"this",
"->",
"fieldModel",
"=",
"$",
"this",
"->",
"dispatcher",
"->",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'mautic.lead.model.field'",
")",
";",
"$",
"this",
"->",
"selectParts",
"=",
"$",
"this",
"->",
"query",
"->",
"getQueryPart",
"(",
"'select'",
")",
";",
"$",
"this",
"->",
"orderByParts",
"=",
"$",
"this",
"->",
"query",
"->",
"getQueryPart",
"(",
"'orderBy'",
")",
";",
"$",
"this",
"->",
"groupByParts",
"=",
"$",
"this",
"->",
"query",
"->",
"getQueryPart",
"(",
"'groupBy'",
")",
";",
"$",
"this",
"->",
"filters",
"=",
"$",
"this",
"->",
"event",
"->",
"getReport",
"(",
")",
"->",
"getFilters",
"(",
")",
";",
"$",
"this",
"->",
"where",
"=",
"$",
"this",
"->",
"query",
"->",
"getQueryPart",
"(",
"'where'",
")",
";",
"$",
"this",
"->",
"fieldTables",
"=",
"isset",
"(",
"$",
"this",
"->",
"fieldTables",
")",
"?",
"$",
"this",
"->",
"fieldTables",
":",
"[",
"]",
";",
"$",
"this",
"->",
"count",
"=",
"0",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"extendedFields",
")",
"{",
"// Previous method deprecated:",
"// $fields = $this->fieldModel->getEntities(",
"// [",
"// [",
"// 'column' => 'f.isPublished',",
"// 'expr' => 'eq',",
"// 'value' => true,",
"// ],",
"// 'force' => [",
"// 'column' => 'f.object',",
"// 'expr' => 'in',",
"// 'value' => ['extendedField', 'extendedFieldSecure'],",
"// ],",
"// 'hydration_mode' => 'HYDRATE_ARRAY',",
"// ]",
"// );",
"// // Key by alias.",
"// foreach ($fields as $field) {",
"// $this->extendedFields[$field['alias']] = $field;",
"// }",
"$",
"this",
"->",
"extendedFields",
"=",
"$",
"this",
"->",
"fieldModel",
"->",
"getExtendedFields",
"(",
")",
";",
"}",
"$",
"this",
"->",
"alterSelect",
"(",
")",
";",
"if",
"(",
"method_exists",
"(",
"$",
"this",
"->",
"event",
",",
"'getQuery'",
")",
")",
"{",
"// identify ReportQueryEvent instance in backwards compatible way",
"$",
"this",
"->",
"alterOrderBy",
"(",
")",
";",
"}",
"$",
"this",
"->",
"alterGroupBy",
"(",
")",
";",
"$",
"this",
"->",
"alterWhere",
"(",
")",
";",
"$",
"this",
"->",
"query",
"->",
"select",
"(",
"$",
"this",
"->",
"selectParts",
")",
";",
"if",
"(",
"method_exists",
"(",
"$",
"this",
"->",
"event",
",",
"'getQuery'",
")",
"&&",
"!",
"empty",
"(",
"$",
"this",
"->",
"orderByParts",
")",
")",
"{",
"$",
"orderBy",
"=",
"implode",
"(",
"','",
",",
"$",
"this",
"->",
"orderByParts",
")",
";",
"$",
"this",
"->",
"query",
"->",
"add",
"(",
"'orderBy'",
",",
"$",
"orderBy",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"groupByParts",
")",
")",
"{",
"$",
"this",
"->",
"query",
"->",
"groupBy",
"(",
"$",
"this",
"->",
"groupByParts",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"where",
")",
")",
"{",
"$",
"this",
"->",
"query",
"->",
"where",
"(",
"$",
"this",
"->",
"where",
")",
";",
"}",
"}"
]
| helper method to convert queries with extendedField optins
in select, orderBy and GroupBy to work with the
extendedField schema. | [
"helper",
"method",
"to",
"convert",
"queries",
"with",
"extendedField",
"optins",
"in",
"select",
"orderBy",
"and",
"GroupBy",
"to",
"work",
"with",
"the",
"extendedField",
"schema",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/EventListener/ReportSubscriber.php#L142-L194 | train |
TheDMSGroup/mautic-extended-field | Model/ExtendedFieldModel.php | ExtendedFieldModel.getExtendedFields | public function getExtendedFields()
{
$result = [];
$fields = $this->getEntities(
[
'filter' => [
'where' => [
[
'expr' => 'orX',
'val' => [
['column' => 'f.object', 'expr' => 'eq', 'value' => 'extendedField'],
['column' => 'f.object', 'expr' => 'eq', 'value' => 'extendedFieldSecure'],
],
],
],
],
'hydration_mode' => 'HYDRATE_ARRAY',
]
);
foreach ($fields as $field) {
$result[$field['alias']] = $field;
}
return $result;
} | php | public function getExtendedFields()
{
$result = [];
$fields = $this->getEntities(
[
'filter' => [
'where' => [
[
'expr' => 'orX',
'val' => [
['column' => 'f.object', 'expr' => 'eq', 'value' => 'extendedField'],
['column' => 'f.object', 'expr' => 'eq', 'value' => 'extendedFieldSecure'],
],
],
],
],
'hydration_mode' => 'HYDRATE_ARRAY',
]
);
foreach ($fields as $field) {
$result[$field['alias']] = $field;
}
return $result;
} | [
"public",
"function",
"getExtendedFields",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"fields",
"=",
"$",
"this",
"->",
"getEntities",
"(",
"[",
"'filter'",
"=>",
"[",
"'where'",
"=>",
"[",
"[",
"'expr'",
"=>",
"'orX'",
",",
"'val'",
"=>",
"[",
"[",
"'column'",
"=>",
"'f.object'",
",",
"'expr'",
"=>",
"'eq'",
",",
"'value'",
"=>",
"'extendedField'",
"]",
",",
"[",
"'column'",
"=>",
"'f.object'",
",",
"'expr'",
"=>",
"'eq'",
",",
"'value'",
"=>",
"'extendedFieldSecure'",
"]",
",",
"]",
",",
"]",
",",
"]",
",",
"]",
",",
"'hydration_mode'",
"=>",
"'HYDRATE_ARRAY'",
",",
"]",
")",
";",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"field",
")",
"{",
"$",
"result",
"[",
"$",
"field",
"[",
"'alias'",
"]",
"]",
"=",
"$",
"field",
";",
"}",
"return",
"$",
"result",
";",
"}"
]
| Method used to get a whitelist of extended fields for query consideration.
@return array | [
"Method",
"used",
"to",
"get",
"a",
"whitelist",
"of",
"extended",
"fields",
"for",
"query",
"consideration",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/Model/ExtendedFieldModel.php#L32-L56 | train |
TheDMSGroup/mautic-extended-field | Model/ExtendedFieldModel.php | ExtendedFieldModel.getEntities | public function getEntities(array $args = [])
{
// @todo - use permission base to exclude secure if necessary.
$replacementFilter = [
'column' => 'f.object',
'expr' => 'neq',
'value' => ['company'],
];
foreach ($args as $type => &$arg) {
if ('filter' === $type) {
foreach ($arg as $key => &$filter) {
if ('force' === $key) {
foreach ($filter as $forceKey => &$forceFilter) {
if (
!empty($forceFilter['column'])
&& 'f.object' == $forceFilter['column']
&& !empty($forceFilter['expr'])
&& 'eq' == $forceFilter['expr']
&& !empty($forceFilter['value'])
&& 'lead' == $forceFilter['value']
) {
$forceFilter = $replacementFilter;
}
}
} elseif ('object' === $key && 'lead' === $filter) {
// Move the filter to force mode in order to replace.
if (!isset($arg['force'])) {
$arg['force'] = [];
}
$arg['force'][] = $replacementFilter;
unset($arg[$key]);
}
}
}
}
return parent::getEntities($args);
} | php | public function getEntities(array $args = [])
{
// @todo - use permission base to exclude secure if necessary.
$replacementFilter = [
'column' => 'f.object',
'expr' => 'neq',
'value' => ['company'],
];
foreach ($args as $type => &$arg) {
if ('filter' === $type) {
foreach ($arg as $key => &$filter) {
if ('force' === $key) {
foreach ($filter as $forceKey => &$forceFilter) {
if (
!empty($forceFilter['column'])
&& 'f.object' == $forceFilter['column']
&& !empty($forceFilter['expr'])
&& 'eq' == $forceFilter['expr']
&& !empty($forceFilter['value'])
&& 'lead' == $forceFilter['value']
) {
$forceFilter = $replacementFilter;
}
}
} elseif ('object' === $key && 'lead' === $filter) {
// Move the filter to force mode in order to replace.
if (!isset($arg['force'])) {
$arg['force'] = [];
}
$arg['force'][] = $replacementFilter;
unset($arg[$key]);
}
}
}
}
return parent::getEntities($args);
} | [
"public",
"function",
"getEntities",
"(",
"array",
"$",
"args",
"=",
"[",
"]",
")",
"{",
"// @todo - use permission base to exclude secure if necessary.",
"$",
"replacementFilter",
"=",
"[",
"'column'",
"=>",
"'f.object'",
",",
"'expr'",
"=>",
"'neq'",
",",
"'value'",
"=>",
"[",
"'company'",
"]",
",",
"]",
";",
"foreach",
"(",
"$",
"args",
"as",
"$",
"type",
"=>",
"&",
"$",
"arg",
")",
"{",
"if",
"(",
"'filter'",
"===",
"$",
"type",
")",
"{",
"foreach",
"(",
"$",
"arg",
"as",
"$",
"key",
"=>",
"&",
"$",
"filter",
")",
"{",
"if",
"(",
"'force'",
"===",
"$",
"key",
")",
"{",
"foreach",
"(",
"$",
"filter",
"as",
"$",
"forceKey",
"=>",
"&",
"$",
"forceFilter",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"forceFilter",
"[",
"'column'",
"]",
")",
"&&",
"'f.object'",
"==",
"$",
"forceFilter",
"[",
"'column'",
"]",
"&&",
"!",
"empty",
"(",
"$",
"forceFilter",
"[",
"'expr'",
"]",
")",
"&&",
"'eq'",
"==",
"$",
"forceFilter",
"[",
"'expr'",
"]",
"&&",
"!",
"empty",
"(",
"$",
"forceFilter",
"[",
"'value'",
"]",
")",
"&&",
"'lead'",
"==",
"$",
"forceFilter",
"[",
"'value'",
"]",
")",
"{",
"$",
"forceFilter",
"=",
"$",
"replacementFilter",
";",
"}",
"}",
"}",
"elseif",
"(",
"'object'",
"===",
"$",
"key",
"&&",
"'lead'",
"===",
"$",
"filter",
")",
"{",
"// Move the filter to force mode in order to replace.",
"if",
"(",
"!",
"isset",
"(",
"$",
"arg",
"[",
"'force'",
"]",
")",
")",
"{",
"$",
"arg",
"[",
"'force'",
"]",
"=",
"[",
"]",
";",
"}",
"$",
"arg",
"[",
"'force'",
"]",
"[",
"]",
"=",
"$",
"replacementFilter",
";",
"unset",
"(",
"$",
"arg",
"[",
"$",
"key",
"]",
")",
";",
"}",
"}",
"}",
"}",
"return",
"parent",
"::",
"getEntities",
"(",
"$",
"args",
")",
";",
"}"
]
| Returns lead custom fields.
Alterations to core:
Include extended objects when various methods attempt to get fields of object 'lead'.
@param $args
@return array | [
"Returns",
"lead",
"custom",
"fields",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/Model/ExtendedFieldModel.php#L68-L105 | train |
TheDMSGroup/mautic-extended-field | Model/ExtendedFieldModel.php | ExtendedFieldModel.saveEntity | public function saveEntity($entity, $unlock = true)
{
if (!$this->isExtendedField($entity)) {
parent::saveEntity($entity, $unlock);
return;
}
if (!$entity instanceof LeadField) {
throw new MethodNotAllowedHttpException(['LeadEntity']);
}
$isNew = $entity->getId() ? false : true;
$this->setTimestamps($entity, $isNew, $unlock);
$alias = $entity->getAlias();
if ($isNew) {
if (empty($alias)) {
$alias = $entity->getName();
}
// clean the alias
$alias = $this->cleanAlias($alias, 'f_', 25);
// make sure alias is not already taken
$repo = $this->getRepository();
$aliases = $repo->getAliases($entity->getId(), false, true, $entity->getObject());
$aliasTag = 1;
$testAlias = $alias;
while (in_array($testAlias, $aliases)) {
$testAlias = $alias.$aliasTag++;
}
$entity->setAlias($testAlias);
}
// Special treatment for time (same as core).
if ('time' == $entity->getType()) {
$entity->setIsListable(false);
}
// Presave and postsave (same as core, but using OverrideLeadFieldRepository).
$event = $this->dispatchEvent('pre_save', $entity, $isNew);
$this->getRepository()->saveEntity($entity);
$this->dispatchEvent('post_save', $entity, $isNew, $event);
// Update order of the other fields (same as core).
$this->reorderFieldsByEntity($entity);
} | php | public function saveEntity($entity, $unlock = true)
{
if (!$this->isExtendedField($entity)) {
parent::saveEntity($entity, $unlock);
return;
}
if (!$entity instanceof LeadField) {
throw new MethodNotAllowedHttpException(['LeadEntity']);
}
$isNew = $entity->getId() ? false : true;
$this->setTimestamps($entity, $isNew, $unlock);
$alias = $entity->getAlias();
if ($isNew) {
if (empty($alias)) {
$alias = $entity->getName();
}
// clean the alias
$alias = $this->cleanAlias($alias, 'f_', 25);
// make sure alias is not already taken
$repo = $this->getRepository();
$aliases = $repo->getAliases($entity->getId(), false, true, $entity->getObject());
$aliasTag = 1;
$testAlias = $alias;
while (in_array($testAlias, $aliases)) {
$testAlias = $alias.$aliasTag++;
}
$entity->setAlias($testAlias);
}
// Special treatment for time (same as core).
if ('time' == $entity->getType()) {
$entity->setIsListable(false);
}
// Presave and postsave (same as core, but using OverrideLeadFieldRepository).
$event = $this->dispatchEvent('pre_save', $entity, $isNew);
$this->getRepository()->saveEntity($entity);
$this->dispatchEvent('post_save', $entity, $isNew, $event);
// Update order of the other fields (same as core).
$this->reorderFieldsByEntity($entity);
} | [
"public",
"function",
"saveEntity",
"(",
"$",
"entity",
",",
"$",
"unlock",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isExtendedField",
"(",
"$",
"entity",
")",
")",
"{",
"parent",
"::",
"saveEntity",
"(",
"$",
"entity",
",",
"$",
"unlock",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"$",
"entity",
"instanceof",
"LeadField",
")",
"{",
"throw",
"new",
"MethodNotAllowedHttpException",
"(",
"[",
"'LeadEntity'",
"]",
")",
";",
"}",
"$",
"isNew",
"=",
"$",
"entity",
"->",
"getId",
"(",
")",
"?",
"false",
":",
"true",
";",
"$",
"this",
"->",
"setTimestamps",
"(",
"$",
"entity",
",",
"$",
"isNew",
",",
"$",
"unlock",
")",
";",
"$",
"alias",
"=",
"$",
"entity",
"->",
"getAlias",
"(",
")",
";",
"if",
"(",
"$",
"isNew",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"alias",
")",
")",
"{",
"$",
"alias",
"=",
"$",
"entity",
"->",
"getName",
"(",
")",
";",
"}",
"// clean the alias",
"$",
"alias",
"=",
"$",
"this",
"->",
"cleanAlias",
"(",
"$",
"alias",
",",
"'f_'",
",",
"25",
")",
";",
"// make sure alias is not already taken",
"$",
"repo",
"=",
"$",
"this",
"->",
"getRepository",
"(",
")",
";",
"$",
"aliases",
"=",
"$",
"repo",
"->",
"getAliases",
"(",
"$",
"entity",
"->",
"getId",
"(",
")",
",",
"false",
",",
"true",
",",
"$",
"entity",
"->",
"getObject",
"(",
")",
")",
";",
"$",
"aliasTag",
"=",
"1",
";",
"$",
"testAlias",
"=",
"$",
"alias",
";",
"while",
"(",
"in_array",
"(",
"$",
"testAlias",
",",
"$",
"aliases",
")",
")",
"{",
"$",
"testAlias",
"=",
"$",
"alias",
".",
"$",
"aliasTag",
"++",
";",
"}",
"$",
"entity",
"->",
"setAlias",
"(",
"$",
"testAlias",
")",
";",
"}",
"// Special treatment for time (same as core).",
"if",
"(",
"'time'",
"==",
"$",
"entity",
"->",
"getType",
"(",
")",
")",
"{",
"$",
"entity",
"->",
"setIsListable",
"(",
"false",
")",
";",
"}",
"// Presave and postsave (same as core, but using OverrideLeadFieldRepository).",
"$",
"event",
"=",
"$",
"this",
"->",
"dispatchEvent",
"(",
"'pre_save'",
",",
"$",
"entity",
",",
"$",
"isNew",
")",
";",
"$",
"this",
"->",
"getRepository",
"(",
")",
"->",
"saveEntity",
"(",
"$",
"entity",
")",
";",
"$",
"this",
"->",
"dispatchEvent",
"(",
"'post_save'",
",",
"$",
"entity",
",",
"$",
"isNew",
",",
"$",
"event",
")",
";",
"// Update order of the other fields (same as core).",
"$",
"this",
"->",
"reorderFieldsByEntity",
"(",
"$",
"entity",
")",
";",
"}"
]
| Save an extended field.
Alterations to core:
The save uses OverrideLeadFieldRepository if the field is extended.
We also prevent alias collisions (as it wouldn't be a column definition).
@param object $entity
@param bool $unlock
@throws DBALException
@throws DriverException
@throws \Doctrine\DBAL\Schema\SchemaException
@throws \Mautic\CoreBundle\Exception\SchemaException | [
"Save",
"an",
"extended",
"field",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/Model/ExtendedFieldModel.php#L122-L168 | train |
TheDMSGroup/mautic-extended-field | Model/ExtendedFieldModel.php | ExtendedFieldModel.getLookupResults | public function getLookupResults($type, $filter = '', $limit = 10)
{
return $this->getRepository()->getValueList($type, $filter, $limit);
} | php | public function getLookupResults($type, $filter = '', $limit = 10)
{
return $this->getRepository()->getValueList($type, $filter, $limit);
} | [
"public",
"function",
"getLookupResults",
"(",
"$",
"type",
",",
"$",
"filter",
"=",
"''",
",",
"$",
"limit",
"=",
"10",
")",
"{",
"return",
"$",
"this",
"->",
"getRepository",
"(",
")",
"->",
"getValueList",
"(",
"$",
"type",
",",
"$",
"filter",
",",
"$",
"limit",
")",
";",
"}"
]
| Get list of custom field values for autopopulate fields.
Alterations to core:
Uses OverrideLeadFieldRepository.
@param $type
@param $filter
@param $limit
@return array | [
"Get",
"list",
"of",
"custom",
"field",
"values",
"for",
"autopopulate",
"fields",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/Model/ExtendedFieldModel.php#L202-L205 | train |
TheDMSGroup/mautic-extended-field | Entity/OverrideLeadRepository.php | OverrideLeadRepository.addCatchAllWhereClause | protected function addCatchAllWhereClause($q, $filter)
{
$filterContainsPhone = $this->filterContainsPhone($filter); // might need to add a '+' so pass by reference
$filterContainsEmail = $this->filterContainsEmail($filter);
$filterContainsZip = $this->filterContainsZip($filter);
$columns = array_merge(
$filterContainsPhone,
$filterContainsEmail,
$filterContainsZip
);
if (empty($columns)) {
$columns = array_merge(
[
'l.firstname',
'l.lastname',
'l.company',
'l.city',
'l.state',
'l.country',
],
$this->availableSocialFields
);
}
return $this->addStandardCatchAllWhereClause($q, $filter, $columns);
} | php | protected function addCatchAllWhereClause($q, $filter)
{
$filterContainsPhone = $this->filterContainsPhone($filter); // might need to add a '+' so pass by reference
$filterContainsEmail = $this->filterContainsEmail($filter);
$filterContainsZip = $this->filterContainsZip($filter);
$columns = array_merge(
$filterContainsPhone,
$filterContainsEmail,
$filterContainsZip
);
if (empty($columns)) {
$columns = array_merge(
[
'l.firstname',
'l.lastname',
'l.company',
'l.city',
'l.state',
'l.country',
],
$this->availableSocialFields
);
}
return $this->addStandardCatchAllWhereClause($q, $filter, $columns);
} | [
"protected",
"function",
"addCatchAllWhereClause",
"(",
"$",
"q",
",",
"$",
"filter",
")",
"{",
"$",
"filterContainsPhone",
"=",
"$",
"this",
"->",
"filterContainsPhone",
"(",
"$",
"filter",
")",
";",
"// might need to add a '+' so pass by reference",
"$",
"filterContainsEmail",
"=",
"$",
"this",
"->",
"filterContainsEmail",
"(",
"$",
"filter",
")",
";",
"$",
"filterContainsZip",
"=",
"$",
"this",
"->",
"filterContainsZip",
"(",
"$",
"filter",
")",
";",
"$",
"columns",
"=",
"array_merge",
"(",
"$",
"filterContainsPhone",
",",
"$",
"filterContainsEmail",
",",
"$",
"filterContainsZip",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"columns",
")",
")",
"{",
"$",
"columns",
"=",
"array_merge",
"(",
"[",
"'l.firstname'",
",",
"'l.lastname'",
",",
"'l.company'",
",",
"'l.city'",
",",
"'l.state'",
",",
"'l.country'",
",",
"]",
",",
"$",
"this",
"->",
"availableSocialFields",
")",
";",
"}",
"return",
"$",
"this",
"->",
"addStandardCatchAllWhereClause",
"(",
"$",
"q",
",",
"$",
"filter",
",",
"$",
"columns",
")",
";",
"}"
]
| Adds the "catch all" where clause to the QueryBuilder.
@param \Doctrine\ORM\QueryBuilder|\Doctrine\DBAL\Query\QueryBuilder $q
@param $filter
@return array | [
"Adds",
"the",
"catch",
"all",
"where",
"clause",
"to",
"the",
"QueryBuilder",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/Entity/OverrideLeadRepository.php#L355-L382 | train |
TheDMSGroup/mautic-extended-field | Entity/ExtendedFieldRepositoryTrait.php | ExtendedFieldRepositoryTrait.getExtendedFieldValuesMultiple | private function getExtendedFieldValuesMultiple(
$extendedFieldList = [],
$leadIds = []
) {
/** @var EntityManager $em */
$em = $this->getEntityManager();
$leadIdsStr = "'".implode("','", $leadIds)."'";
$selects = [];
foreach (['string', 'float', 'boolean', 'date', 'datetime', 'time', 'text'] as $data_type) {
foreach (['', '_secure'] as $secure) {
$xrefTable = MAUTIC_TABLE_PREFIX."lead_fields_leads_{$data_type}{$secure}_xref";
$selects[] = <<<EOSQL
SELECT lead_id, lead_field_id, value, '{$data_type}' AS data_type
FROM {$xrefTable}
WHERE lead_id IN ({$leadIdsStr})
EOSQL;
}
}
$xrefQuery = implode("\nUNION\n", $selects);
$leadsTable = $em->getRepository('MauticLeadBundle:Lead')->getTableName();
$lt = $em->getRepository('MauticLeadBundle:Lead')->getTableAlias();
$leadFieldsTable = $em->getRepository('MauticLeadBundle:LeadField')->getTableName();
$lft = $em->getRepository('MauticLeadBundle:LeadField')->getTableAlias();
$where = "{$lft}.object IN ('extendedField','extendedFieldSecure') ";
if (!empty($extendedFieldList)) {
$ids = array_map(
function ($e) {
return $e['id'];
},
$extendedFieldList
);
$leadFiieldIdStr = "'".implode("','", $ids)."'";
$where = "{$lft}.id IN ({$leadFiieldIdStr}) ";
}
$sql = <<<EOSQL
SELECT x.lead_id, x.alias, v.value, v.data_type
FROM
(
SELECT {$lt}.id AS lead_id,
{$lft}.id as lead_field_id,
{$lft}.alias
FROM {$leadsTable} {$lt} CROSS JOIN {$leadFieldsTable} {$lft}
WHERE {$where}
AND {$lt}.id IN ({$leadIdsStr})
) x
LEFT JOIN
(
{$xrefQuery}
) v USING (lead_id, lead_field_id)
EOSQL;
$query = $em->getConnection()->prepare($sql);
$query->execute();
$results = $query->fetchAll();
// Group results by leadId.
$leads = [];
foreach ($results as $row => $result) {
$leads[$result['lead_id']][$result['alias']] = $result['value'];
unset($results[$row]);
}
return $leads;
} | php | private function getExtendedFieldValuesMultiple(
$extendedFieldList = [],
$leadIds = []
) {
/** @var EntityManager $em */
$em = $this->getEntityManager();
$leadIdsStr = "'".implode("','", $leadIds)."'";
$selects = [];
foreach (['string', 'float', 'boolean', 'date', 'datetime', 'time', 'text'] as $data_type) {
foreach (['', '_secure'] as $secure) {
$xrefTable = MAUTIC_TABLE_PREFIX."lead_fields_leads_{$data_type}{$secure}_xref";
$selects[] = <<<EOSQL
SELECT lead_id, lead_field_id, value, '{$data_type}' AS data_type
FROM {$xrefTable}
WHERE lead_id IN ({$leadIdsStr})
EOSQL;
}
}
$xrefQuery = implode("\nUNION\n", $selects);
$leadsTable = $em->getRepository('MauticLeadBundle:Lead')->getTableName();
$lt = $em->getRepository('MauticLeadBundle:Lead')->getTableAlias();
$leadFieldsTable = $em->getRepository('MauticLeadBundle:LeadField')->getTableName();
$lft = $em->getRepository('MauticLeadBundle:LeadField')->getTableAlias();
$where = "{$lft}.object IN ('extendedField','extendedFieldSecure') ";
if (!empty($extendedFieldList)) {
$ids = array_map(
function ($e) {
return $e['id'];
},
$extendedFieldList
);
$leadFiieldIdStr = "'".implode("','", $ids)."'";
$where = "{$lft}.id IN ({$leadFiieldIdStr}) ";
}
$sql = <<<EOSQL
SELECT x.lead_id, x.alias, v.value, v.data_type
FROM
(
SELECT {$lt}.id AS lead_id,
{$lft}.id as lead_field_id,
{$lft}.alias
FROM {$leadsTable} {$lt} CROSS JOIN {$leadFieldsTable} {$lft}
WHERE {$where}
AND {$lt}.id IN ({$leadIdsStr})
) x
LEFT JOIN
(
{$xrefQuery}
) v USING (lead_id, lead_field_id)
EOSQL;
$query = $em->getConnection()->prepare($sql);
$query->execute();
$results = $query->fetchAll();
// Group results by leadId.
$leads = [];
foreach ($results as $row => $result) {
$leads[$result['lead_id']][$result['alias']] = $result['value'];
unset($results[$row]);
}
return $leads;
} | [
"private",
"function",
"getExtendedFieldValuesMultiple",
"(",
"$",
"extendedFieldList",
"=",
"[",
"]",
",",
"$",
"leadIds",
"=",
"[",
"]",
")",
"{",
"/** @var EntityManager $em */",
"$",
"em",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
";",
"$",
"leadIdsStr",
"=",
"\"'\"",
".",
"implode",
"(",
"\"','\"",
",",
"$",
"leadIds",
")",
".",
"\"'\"",
";",
"$",
"selects",
"=",
"[",
"]",
";",
"foreach",
"(",
"[",
"'string'",
",",
"'float'",
",",
"'boolean'",
",",
"'date'",
",",
"'datetime'",
",",
"'time'",
",",
"'text'",
"]",
"as",
"$",
"data_type",
")",
"{",
"foreach",
"(",
"[",
"''",
",",
"'_secure'",
"]",
"as",
"$",
"secure",
")",
"{",
"$",
"xrefTable",
"=",
"MAUTIC_TABLE_PREFIX",
".",
"\"lead_fields_leads_{$data_type}{$secure}_xref\"",
";",
"$",
"selects",
"[",
"]",
"=",
" <<<EOSQL\nSELECT lead_id, lead_field_id, value, '{$data_type}' AS data_type \nFROM {$xrefTable}\nWHERE lead_id IN ({$leadIdsStr})\nEOSQL",
";",
"}",
"}",
"$",
"xrefQuery",
"=",
"implode",
"(",
"\"\\nUNION\\n\"",
",",
"$",
"selects",
")",
";",
"$",
"leadsTable",
"=",
"$",
"em",
"->",
"getRepository",
"(",
"'MauticLeadBundle:Lead'",
")",
"->",
"getTableName",
"(",
")",
";",
"$",
"lt",
"=",
"$",
"em",
"->",
"getRepository",
"(",
"'MauticLeadBundle:Lead'",
")",
"->",
"getTableAlias",
"(",
")",
";",
"$",
"leadFieldsTable",
"=",
"$",
"em",
"->",
"getRepository",
"(",
"'MauticLeadBundle:LeadField'",
")",
"->",
"getTableName",
"(",
")",
";",
"$",
"lft",
"=",
"$",
"em",
"->",
"getRepository",
"(",
"'MauticLeadBundle:LeadField'",
")",
"->",
"getTableAlias",
"(",
")",
";",
"$",
"where",
"=",
"\"{$lft}.object IN ('extendedField','extendedFieldSecure') \"",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"extendedFieldList",
")",
")",
"{",
"$",
"ids",
"=",
"array_map",
"(",
"function",
"(",
"$",
"e",
")",
"{",
"return",
"$",
"e",
"[",
"'id'",
"]",
";",
"}",
",",
"$",
"extendedFieldList",
")",
";",
"$",
"leadFiieldIdStr",
"=",
"\"'\"",
".",
"implode",
"(",
"\"','\"",
",",
"$",
"ids",
")",
".",
"\"'\"",
";",
"$",
"where",
"=",
"\"{$lft}.id IN ({$leadFiieldIdStr}) \"",
";",
"}",
"$",
"sql",
"=",
" <<<EOSQL\nSELECT x.lead_id, x.alias, v.value, v.data_type\nFROM\n(\n SELECT {$lt}.id AS lead_id,\n {$lft}.id as lead_field_id,\n {$lft}.alias\n FROM {$leadsTable} {$lt} CROSS JOIN {$leadFieldsTable} {$lft}\n WHERE {$where}\n AND {$lt}.id IN ({$leadIdsStr})\n) x\nLEFT JOIN\n(\n {$xrefQuery}\n) v USING (lead_id, lead_field_id)\nEOSQL",
";",
"$",
"query",
"=",
"$",
"em",
"->",
"getConnection",
"(",
")",
"->",
"prepare",
"(",
"$",
"sql",
")",
";",
"$",
"query",
"->",
"execute",
"(",
")",
";",
"$",
"results",
"=",
"$",
"query",
"->",
"fetchAll",
"(",
")",
";",
"// Group results by leadId.",
"$",
"leads",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"results",
"as",
"$",
"row",
"=>",
"$",
"result",
")",
"{",
"$",
"leads",
"[",
"$",
"result",
"[",
"'lead_id'",
"]",
"]",
"[",
"$",
"result",
"[",
"'alias'",
"]",
"]",
"=",
"$",
"result",
"[",
"'value'",
"]",
";",
"unset",
"(",
"$",
"results",
"[",
"$",
"row",
"]",
")",
";",
"}",
"return",
"$",
"leads",
";",
"}"
]
| Join all the EAV data into one consumable array.
@param array $extendedFieldList
@param array $leadIds
@return array | [
"Join",
"all",
"the",
"EAV",
"data",
"into",
"one",
"consumable",
"array",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/Entity/ExtendedFieldRepositoryTrait.php#L147-L216 | train |
TheDMSGroup/mautic-extended-field | Entity/ExtendedFieldRepositoryTrait.php | ExtendedFieldRepositoryTrait.getExtendedFieldFilters | private function getExtendedFieldFilters($args, $extendedFieldList)
{
$result = [];
if (isset($args['filter'])) {
foreach (array_keys($extendedFieldList) as $alias) {
// @todo - Instead of strpos use regex w/ word boundry, loop below needs cleanup.
if (
isset($args['filter']['string'])
&& (
(
is_string($args['filter']['string']) && false !== strpos(
$args['filter']['string'],
$alias
)
)
|| (
is_string($args['filter']['force']) && false !== strpos(
$args['filter']['force'],
$alias
)
)
)
) {
// field is in the filter array somewhere
$result[$alias] = $extendedFieldList[$alias];
continue;
}
$extendedFieldLength = strlen($alias);
foreach (['string', 'force'] as $type) {
if (
isset($args['filter'][$type])
&& is_array($args['filter'][$type])
) {
foreach ($args['filter'][$type] as $filter) {
if (isset($filter['column'])) {
if (substr(
$filter['column'],
strlen($filter['column']) - $extendedFieldLength - 1
) == '.'.$alias) {
$result[$alias] = $extendedFieldList[$alias];
continue;
}
}
}
}
}
}
}
return $result;
} | php | private function getExtendedFieldFilters($args, $extendedFieldList)
{
$result = [];
if (isset($args['filter'])) {
foreach (array_keys($extendedFieldList) as $alias) {
// @todo - Instead of strpos use regex w/ word boundry, loop below needs cleanup.
if (
isset($args['filter']['string'])
&& (
(
is_string($args['filter']['string']) && false !== strpos(
$args['filter']['string'],
$alias
)
)
|| (
is_string($args['filter']['force']) && false !== strpos(
$args['filter']['force'],
$alias
)
)
)
) {
// field is in the filter array somewhere
$result[$alias] = $extendedFieldList[$alias];
continue;
}
$extendedFieldLength = strlen($alias);
foreach (['string', 'force'] as $type) {
if (
isset($args['filter'][$type])
&& is_array($args['filter'][$type])
) {
foreach ($args['filter'][$type] as $filter) {
if (isset($filter['column'])) {
if (substr(
$filter['column'],
strlen($filter['column']) - $extendedFieldLength - 1
) == '.'.$alias) {
$result[$alias] = $extendedFieldList[$alias];
continue;
}
}
}
}
}
}
}
return $result;
} | [
"private",
"function",
"getExtendedFieldFilters",
"(",
"$",
"args",
",",
"$",
"extendedFieldList",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"args",
"[",
"'filter'",
"]",
")",
")",
"{",
"foreach",
"(",
"array_keys",
"(",
"$",
"extendedFieldList",
")",
"as",
"$",
"alias",
")",
"{",
"// @todo - Instead of strpos use regex w/ word boundry, loop below needs cleanup.",
"if",
"(",
"isset",
"(",
"$",
"args",
"[",
"'filter'",
"]",
"[",
"'string'",
"]",
")",
"&&",
"(",
"(",
"is_string",
"(",
"$",
"args",
"[",
"'filter'",
"]",
"[",
"'string'",
"]",
")",
"&&",
"false",
"!==",
"strpos",
"(",
"$",
"args",
"[",
"'filter'",
"]",
"[",
"'string'",
"]",
",",
"$",
"alias",
")",
")",
"||",
"(",
"is_string",
"(",
"$",
"args",
"[",
"'filter'",
"]",
"[",
"'force'",
"]",
")",
"&&",
"false",
"!==",
"strpos",
"(",
"$",
"args",
"[",
"'filter'",
"]",
"[",
"'force'",
"]",
",",
"$",
"alias",
")",
")",
")",
")",
"{",
"// field is in the filter array somewhere",
"$",
"result",
"[",
"$",
"alias",
"]",
"=",
"$",
"extendedFieldList",
"[",
"$",
"alias",
"]",
";",
"continue",
";",
"}",
"$",
"extendedFieldLength",
"=",
"strlen",
"(",
"$",
"alias",
")",
";",
"foreach",
"(",
"[",
"'string'",
",",
"'force'",
"]",
"as",
"$",
"type",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"args",
"[",
"'filter'",
"]",
"[",
"$",
"type",
"]",
")",
"&&",
"is_array",
"(",
"$",
"args",
"[",
"'filter'",
"]",
"[",
"$",
"type",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"args",
"[",
"'filter'",
"]",
"[",
"$",
"type",
"]",
"as",
"$",
"filter",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"filter",
"[",
"'column'",
"]",
")",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"filter",
"[",
"'column'",
"]",
",",
"strlen",
"(",
"$",
"filter",
"[",
"'column'",
"]",
")",
"-",
"$",
"extendedFieldLength",
"-",
"1",
")",
"==",
"'.'",
".",
"$",
"alias",
")",
"{",
"$",
"result",
"[",
"$",
"alias",
"]",
"=",
"$",
"extendedFieldList",
"[",
"$",
"alias",
"]",
";",
"continue",
";",
"}",
"}",
"}",
"}",
"}",
"}",
"}",
"return",
"$",
"result",
";",
"}"
]
| Discern search filters that are bound to extended fields.
@param string|array $args
@param array $extendedFieldList
@return array | [
"Discern",
"search",
"filters",
"that",
"are",
"bound",
"to",
"extended",
"fields",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/Entity/ExtendedFieldRepositoryTrait.php#L530-L580 | train |
TheDMSGroup/mautic-extended-field | Entity/OverrideLeadFieldRepository.php | OverrideLeadFieldRepository.getExtendedField | private function getExtendedField($alias)
{
$qf = $this->_em->getConnection()->createQueryBuilder();
$qf->select('lf.id, lf.object, lf.type, lf.alias, lf.field_group as "group", lf.object, lf.label')
->from(MAUTIC_TABLE_PREFIX.'lead_fields', 'lf')
->where(
$qf->expr()->andX(
$qf->expr()->eq('lf.alias', ':alias'),
$qf->expr()->orX(
$qf->expr()->eq('lf.object', $qf->expr()->literal('extendedField')),
$qf->expr()->eq('lf.object', $qf->expr()->literal('extendedFieldSecure'))
)
)
)
->setParameter('alias', $alias);
return $qf->execute()->fetch();
} | php | private function getExtendedField($alias)
{
$qf = $this->_em->getConnection()->createQueryBuilder();
$qf->select('lf.id, lf.object, lf.type, lf.alias, lf.field_group as "group", lf.object, lf.label')
->from(MAUTIC_TABLE_PREFIX.'lead_fields', 'lf')
->where(
$qf->expr()->andX(
$qf->expr()->eq('lf.alias', ':alias'),
$qf->expr()->orX(
$qf->expr()->eq('lf.object', $qf->expr()->literal('extendedField')),
$qf->expr()->eq('lf.object', $qf->expr()->literal('extendedFieldSecure'))
)
)
)
->setParameter('alias', $alias);
return $qf->execute()->fetch();
} | [
"private",
"function",
"getExtendedField",
"(",
"$",
"alias",
")",
"{",
"$",
"qf",
"=",
"$",
"this",
"->",
"_em",
"->",
"getConnection",
"(",
")",
"->",
"createQueryBuilder",
"(",
")",
";",
"$",
"qf",
"->",
"select",
"(",
"'lf.id, lf.object, lf.type, lf.alias, lf.field_group as \"group\", lf.object, lf.label'",
")",
"->",
"from",
"(",
"MAUTIC_TABLE_PREFIX",
".",
"'lead_fields'",
",",
"'lf'",
")",
"->",
"where",
"(",
"$",
"qf",
"->",
"expr",
"(",
")",
"->",
"andX",
"(",
"$",
"qf",
"->",
"expr",
"(",
")",
"->",
"eq",
"(",
"'lf.alias'",
",",
"':alias'",
")",
",",
"$",
"qf",
"->",
"expr",
"(",
")",
"->",
"orX",
"(",
"$",
"qf",
"->",
"expr",
"(",
")",
"->",
"eq",
"(",
"'lf.object'",
",",
"$",
"qf",
"->",
"expr",
"(",
")",
"->",
"literal",
"(",
"'extendedField'",
")",
")",
",",
"$",
"qf",
"->",
"expr",
"(",
")",
"->",
"eq",
"(",
"'lf.object'",
",",
"$",
"qf",
"->",
"expr",
"(",
")",
"->",
"literal",
"(",
"'extendedFieldSecure'",
")",
")",
")",
")",
")",
"->",
"setParameter",
"(",
"'alias'",
",",
"$",
"alias",
")",
";",
"return",
"$",
"qf",
"->",
"execute",
"(",
")",
"->",
"fetch",
"(",
")",
";",
"}"
]
| Get an extended field given the field alias.
@param string $alias
@return null|array | [
"Get",
"an",
"extended",
"field",
"given",
"the",
"field",
"alias",
"."
]
| f8b3ef2101ac61d5225cac302c56d31a87eb5508 | https://github.com/TheDMSGroup/mautic-extended-field/blob/f8b3ef2101ac61d5225cac302c56d31a87eb5508/Entity/OverrideLeadFieldRepository.php#L221-L238 | train |
jasny/twig-extensions | src/DateExtension.php | DateExtension.valueToDateTime | protected function valueToDateTime($date)
{
if (!$date instanceof \DateTime) {
$date = is_int($date) ? \DateTime::createFromFormat('U', $date) : new \DateTime((string)$date);
}
return $date;
} | php | protected function valueToDateTime($date)
{
if (!$date instanceof \DateTime) {
$date = is_int($date) ? \DateTime::createFromFormat('U', $date) : new \DateTime((string)$date);
}
return $date;
} | [
"protected",
"function",
"valueToDateTime",
"(",
"$",
"date",
")",
"{",
"if",
"(",
"!",
"$",
"date",
"instanceof",
"\\",
"DateTime",
")",
"{",
"$",
"date",
"=",
"is_int",
"(",
"$",
"date",
")",
"?",
"\\",
"DateTime",
"::",
"createFromFormat",
"(",
"'U'",
",",
"$",
"date",
")",
":",
"new",
"\\",
"DateTime",
"(",
"(",
"string",
")",
"$",
"date",
")",
";",
"}",
"return",
"$",
"date",
";",
"}"
]
| Turn a value into a DateTime object
@param string|int|\DateTime $date
@return \DateTime | [
"Turn",
"a",
"value",
"into",
"a",
"DateTime",
"object"
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/DateExtension.php#L53-L60 | train |
jasny/twig-extensions | src/DateExtension.php | DateExtension.getDateFormatter | protected function getDateFormatter($dateFormat, $timeFormat, $calendar)
{
$datetype = isset($dateFormat) ? $this->getFormat($dateFormat) : null;
$timetype = isset($timeFormat) ? $this->getFormat($timeFormat) : null;
$calendarConst = $calendar === 'traditional' ? \IntlDateFormatter::TRADITIONAL : \IntlDateFormatter::GREGORIAN;
$pattern = $this->getDateTimePattern(
isset($datetype) ? $datetype : $dateFormat,
isset($timetype) ? $timetype : $timeFormat,
$calendarConst
);
return new \IntlDateFormatter(\Locale::getDefault(), $datetype, $timetype, null, $calendarConst, $pattern);
} | php | protected function getDateFormatter($dateFormat, $timeFormat, $calendar)
{
$datetype = isset($dateFormat) ? $this->getFormat($dateFormat) : null;
$timetype = isset($timeFormat) ? $this->getFormat($timeFormat) : null;
$calendarConst = $calendar === 'traditional' ? \IntlDateFormatter::TRADITIONAL : \IntlDateFormatter::GREGORIAN;
$pattern = $this->getDateTimePattern(
isset($datetype) ? $datetype : $dateFormat,
isset($timetype) ? $timetype : $timeFormat,
$calendarConst
);
return new \IntlDateFormatter(\Locale::getDefault(), $datetype, $timetype, null, $calendarConst, $pattern);
} | [
"protected",
"function",
"getDateFormatter",
"(",
"$",
"dateFormat",
",",
"$",
"timeFormat",
",",
"$",
"calendar",
")",
"{",
"$",
"datetype",
"=",
"isset",
"(",
"$",
"dateFormat",
")",
"?",
"$",
"this",
"->",
"getFormat",
"(",
"$",
"dateFormat",
")",
":",
"null",
";",
"$",
"timetype",
"=",
"isset",
"(",
"$",
"timeFormat",
")",
"?",
"$",
"this",
"->",
"getFormat",
"(",
"$",
"timeFormat",
")",
":",
"null",
";",
"$",
"calendarConst",
"=",
"$",
"calendar",
"===",
"'traditional'",
"?",
"\\",
"IntlDateFormatter",
"::",
"TRADITIONAL",
":",
"\\",
"IntlDateFormatter",
"::",
"GREGORIAN",
";",
"$",
"pattern",
"=",
"$",
"this",
"->",
"getDateTimePattern",
"(",
"isset",
"(",
"$",
"datetype",
")",
"?",
"$",
"datetype",
":",
"$",
"dateFormat",
",",
"isset",
"(",
"$",
"timetype",
")",
"?",
"$",
"timetype",
":",
"$",
"timeFormat",
",",
"$",
"calendarConst",
")",
";",
"return",
"new",
"\\",
"IntlDateFormatter",
"(",
"\\",
"Locale",
"::",
"getDefault",
"(",
")",
",",
"$",
"datetype",
",",
"$",
"timetype",
",",
"null",
",",
"$",
"calendarConst",
",",
"$",
"pattern",
")",
";",
"}"
]
| Get configured intl date formatter.
@param string|null $dateFormat
@param string|null $timeFormat
@param string $calendar
@return \IntlDateFormatter | [
"Get",
"configured",
"intl",
"date",
"formatter",
"."
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/DateExtension.php#L70-L84 | train |
jasny/twig-extensions | src/DateExtension.php | DateExtension.localDate | public function localDate($date, $format = null, $calendar = 'gregorian')
{
return $this->formatLocal($date, $format, false, $calendar);
} | php | public function localDate($date, $format = null, $calendar = 'gregorian')
{
return $this->formatLocal($date, $format, false, $calendar);
} | [
"public",
"function",
"localDate",
"(",
"$",
"date",
",",
"$",
"format",
"=",
"null",
",",
"$",
"calendar",
"=",
"'gregorian'",
")",
"{",
"return",
"$",
"this",
"->",
"formatLocal",
"(",
"$",
"date",
",",
"$",
"format",
",",
"false",
",",
"$",
"calendar",
")",
";",
"}"
]
| Format the date value as a string based on the current locale
@param DateTime|int|string $date
@param string $format null, 'short', 'medium', 'long', 'full' or pattern
@param string $calendar 'gregorian' or 'traditional'
@return string | [
"Format",
"the",
"date",
"value",
"as",
"a",
"string",
"based",
"on",
"the",
"current",
"locale"
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/DateExtension.php#L202-L205 | train |
jasny/twig-extensions | src/DateExtension.php | DateExtension.localTime | public function localTime($date, $format = 'short', $calendar = 'gregorian')
{
return $this->formatLocal($date, false, $format, $calendar);
} | php | public function localTime($date, $format = 'short', $calendar = 'gregorian')
{
return $this->formatLocal($date, false, $format, $calendar);
} | [
"public",
"function",
"localTime",
"(",
"$",
"date",
",",
"$",
"format",
"=",
"'short'",
",",
"$",
"calendar",
"=",
"'gregorian'",
")",
"{",
"return",
"$",
"this",
"->",
"formatLocal",
"(",
"$",
"date",
",",
"false",
",",
"$",
"format",
",",
"$",
"calendar",
")",
";",
"}"
]
| Format the time value as a string based on the current locale
@param DateTime|int|string $date
@param string $format 'short', 'medium', 'long', 'full' or pattern
@param string $calendar 'gregorian' or 'traditional'
@return string | [
"Format",
"the",
"time",
"value",
"as",
"a",
"string",
"based",
"on",
"the",
"current",
"locale"
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/DateExtension.php#L215-L218 | train |
jasny/twig-extensions | src/DateExtension.php | DateExtension.splitDuration | protected function splitDuration($seconds, $max)
{
if ($max < 1 || $seconds < 60) {
return [$seconds];
}
$minutes = floor($seconds / 60);
$seconds = $seconds % 60;
if ($max < 2 || $minutes < 60) {
return [$seconds, $minutes];
}
$hours = floor($minutes / 60);
$minutes = $minutes % 60;
if ($max < 3 || $hours < 24) {
return [$seconds, $minutes, $hours];
}
$days = floor($hours / 24);
$hours = $hours % 24;
if ($max < 4 || $days < 7) {
return [$seconds, $minutes, $hours, $days];
}
$weeks = floor($days / 7);
$days = $days % 7;
if ($max < 5 || $weeks < 52) {
return [$seconds, $minutes, $hours, $days, $weeks];
}
$years = floor($weeks / 52);
$weeks = $weeks % 52;
return [$seconds, $minutes, $hours, $days, $weeks, $years];
} | php | protected function splitDuration($seconds, $max)
{
if ($max < 1 || $seconds < 60) {
return [$seconds];
}
$minutes = floor($seconds / 60);
$seconds = $seconds % 60;
if ($max < 2 || $minutes < 60) {
return [$seconds, $minutes];
}
$hours = floor($minutes / 60);
$minutes = $minutes % 60;
if ($max < 3 || $hours < 24) {
return [$seconds, $minutes, $hours];
}
$days = floor($hours / 24);
$hours = $hours % 24;
if ($max < 4 || $days < 7) {
return [$seconds, $minutes, $hours, $days];
}
$weeks = floor($days / 7);
$days = $days % 7;
if ($max < 5 || $weeks < 52) {
return [$seconds, $minutes, $hours, $days, $weeks];
}
$years = floor($weeks / 52);
$weeks = $weeks % 52;
return [$seconds, $minutes, $hours, $days, $weeks, $years];
} | [
"protected",
"function",
"splitDuration",
"(",
"$",
"seconds",
",",
"$",
"max",
")",
"{",
"if",
"(",
"$",
"max",
"<",
"1",
"||",
"$",
"seconds",
"<",
"60",
")",
"{",
"return",
"[",
"$",
"seconds",
"]",
";",
"}",
"$",
"minutes",
"=",
"floor",
"(",
"$",
"seconds",
"/",
"60",
")",
";",
"$",
"seconds",
"=",
"$",
"seconds",
"%",
"60",
";",
"if",
"(",
"$",
"max",
"<",
"2",
"||",
"$",
"minutes",
"<",
"60",
")",
"{",
"return",
"[",
"$",
"seconds",
",",
"$",
"minutes",
"]",
";",
"}",
"$",
"hours",
"=",
"floor",
"(",
"$",
"minutes",
"/",
"60",
")",
";",
"$",
"minutes",
"=",
"$",
"minutes",
"%",
"60",
";",
"if",
"(",
"$",
"max",
"<",
"3",
"||",
"$",
"hours",
"<",
"24",
")",
"{",
"return",
"[",
"$",
"seconds",
",",
"$",
"minutes",
",",
"$",
"hours",
"]",
";",
"}",
"$",
"days",
"=",
"floor",
"(",
"$",
"hours",
"/",
"24",
")",
";",
"$",
"hours",
"=",
"$",
"hours",
"%",
"24",
";",
"if",
"(",
"$",
"max",
"<",
"4",
"||",
"$",
"days",
"<",
"7",
")",
"{",
"return",
"[",
"$",
"seconds",
",",
"$",
"minutes",
",",
"$",
"hours",
",",
"$",
"days",
"]",
";",
"}",
"$",
"weeks",
"=",
"floor",
"(",
"$",
"days",
"/",
"7",
")",
";",
"$",
"days",
"=",
"$",
"days",
"%",
"7",
";",
"if",
"(",
"$",
"max",
"<",
"5",
"||",
"$",
"weeks",
"<",
"52",
")",
"{",
"return",
"[",
"$",
"seconds",
",",
"$",
"minutes",
",",
"$",
"hours",
",",
"$",
"days",
",",
"$",
"weeks",
"]",
";",
"}",
"$",
"years",
"=",
"floor",
"(",
"$",
"weeks",
"/",
"52",
")",
";",
"$",
"weeks",
"=",
"$",
"weeks",
"%",
"52",
";",
"return",
"[",
"$",
"seconds",
",",
"$",
"minutes",
",",
"$",
"hours",
",",
"$",
"days",
",",
"$",
"weeks",
",",
"$",
"years",
"]",
";",
"}"
]
| Split duration into seconds, minutes, hours, days, weeks and years.
@param int $seconds
@return array | [
"Split",
"duration",
"into",
"seconds",
"minutes",
"hours",
"days",
"weeks",
"and",
"years",
"."
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/DateExtension.php#L248-L281 | train |
jasny/twig-extensions | src/DateExtension.php | DateExtension.duration | public function duration($value, $units = ['s', 'm', 'h', 'd', 'w', 'y'], $separator = ' ')
{
if (!isset($value)) {
return null;
}
list($seconds, $minutes, $hours, $days, $weeks, $years) =
$this->splitDuration($value, count($units) - 1) + array_fill(0, 6, null);
$duration = '';
if (isset($years) && isset($units[5])) {
$duration .= $separator . $years . $units[5];
}
if (isset($weeks) && isset($units[4])) {
$duration .= $separator . $weeks . $units[4];
}
if (isset($days) && isset($units[3])) {
$duration .= $separator . $days . $units[3];
}
if (isset($hours) && isset($units[2])) {
$duration .= $separator . $hours . $units[2];
}
if (isset($minutes) && isset($units[1])) {
$duration .= $separator . $minutes . $units[1];
}
if (isset($seconds) && isset($units[0])) {
$duration .= $separator . $seconds . $units[0];
}
return trim($duration, $separator);
} | php | public function duration($value, $units = ['s', 'm', 'h', 'd', 'w', 'y'], $separator = ' ')
{
if (!isset($value)) {
return null;
}
list($seconds, $minutes, $hours, $days, $weeks, $years) =
$this->splitDuration($value, count($units) - 1) + array_fill(0, 6, null);
$duration = '';
if (isset($years) && isset($units[5])) {
$duration .= $separator . $years . $units[5];
}
if (isset($weeks) && isset($units[4])) {
$duration .= $separator . $weeks . $units[4];
}
if (isset($days) && isset($units[3])) {
$duration .= $separator . $days . $units[3];
}
if (isset($hours) && isset($units[2])) {
$duration .= $separator . $hours . $units[2];
}
if (isset($minutes) && isset($units[1])) {
$duration .= $separator . $minutes . $units[1];
}
if (isset($seconds) && isset($units[0])) {
$duration .= $separator . $seconds . $units[0];
}
return trim($duration, $separator);
} | [
"public",
"function",
"duration",
"(",
"$",
"value",
",",
"$",
"units",
"=",
"[",
"'s'",
",",
"'m'",
",",
"'h'",
",",
"'d'",
",",
"'w'",
",",
"'y'",
"]",
",",
"$",
"separator",
"=",
"' '",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"list",
"(",
"$",
"seconds",
",",
"$",
"minutes",
",",
"$",
"hours",
",",
"$",
"days",
",",
"$",
"weeks",
",",
"$",
"years",
")",
"=",
"$",
"this",
"->",
"splitDuration",
"(",
"$",
"value",
",",
"count",
"(",
"$",
"units",
")",
"-",
"1",
")",
"+",
"array_fill",
"(",
"0",
",",
"6",
",",
"null",
")",
";",
"$",
"duration",
"=",
"''",
";",
"if",
"(",
"isset",
"(",
"$",
"years",
")",
"&&",
"isset",
"(",
"$",
"units",
"[",
"5",
"]",
")",
")",
"{",
"$",
"duration",
".=",
"$",
"separator",
".",
"$",
"years",
".",
"$",
"units",
"[",
"5",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"weeks",
")",
"&&",
"isset",
"(",
"$",
"units",
"[",
"4",
"]",
")",
")",
"{",
"$",
"duration",
".=",
"$",
"separator",
".",
"$",
"weeks",
".",
"$",
"units",
"[",
"4",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"days",
")",
"&&",
"isset",
"(",
"$",
"units",
"[",
"3",
"]",
")",
")",
"{",
"$",
"duration",
".=",
"$",
"separator",
".",
"$",
"days",
".",
"$",
"units",
"[",
"3",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"hours",
")",
"&&",
"isset",
"(",
"$",
"units",
"[",
"2",
"]",
")",
")",
"{",
"$",
"duration",
".=",
"$",
"separator",
".",
"$",
"hours",
".",
"$",
"units",
"[",
"2",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"minutes",
")",
"&&",
"isset",
"(",
"$",
"units",
"[",
"1",
"]",
")",
")",
"{",
"$",
"duration",
".=",
"$",
"separator",
".",
"$",
"minutes",
".",
"$",
"units",
"[",
"1",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"seconds",
")",
"&&",
"isset",
"(",
"$",
"units",
"[",
"0",
"]",
")",
")",
"{",
"$",
"duration",
".=",
"$",
"separator",
".",
"$",
"seconds",
".",
"$",
"units",
"[",
"0",
"]",
";",
"}",
"return",
"trim",
"(",
"$",
"duration",
",",
"$",
"separator",
")",
";",
"}"
]
| Calculate duration from seconds.
One year is seen as exactly 52 weeks.
Use null to skip a unit.
@param int $value Time in seconds
@param array $units Time units (seconds, minutes, hours, days, weeks, years)
@param string $separator
@return string | [
"Calculate",
"duration",
"from",
"seconds",
".",
"One",
"year",
"is",
"seen",
"as",
"exactly",
"52",
"weeks",
"."
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/DateExtension.php#L294-L329 | train |
jasny/twig-extensions | src/PcreExtension.php | PcreExtension.assertNoEval | protected function assertNoEval($pattern)
{
$pos = strrpos($pattern, $pattern[0]);
$modifiers = substr($pattern, $pos + 1);
if (strpos($modifiers, 'e') !== false) {
throw new \Twig_Error_Runtime("Using the eval modifier for regular expressions is not allowed");
}
} | php | protected function assertNoEval($pattern)
{
$pos = strrpos($pattern, $pattern[0]);
$modifiers = substr($pattern, $pos + 1);
if (strpos($modifiers, 'e') !== false) {
throw new \Twig_Error_Runtime("Using the eval modifier for regular expressions is not allowed");
}
} | [
"protected",
"function",
"assertNoEval",
"(",
"$",
"pattern",
")",
"{",
"$",
"pos",
"=",
"strrpos",
"(",
"$",
"pattern",
",",
"$",
"pattern",
"[",
"0",
"]",
")",
";",
"$",
"modifiers",
"=",
"substr",
"(",
"$",
"pattern",
",",
"$",
"pos",
"+",
"1",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"modifiers",
",",
"'e'",
")",
"!==",
"false",
")",
"{",
"throw",
"new",
"\\",
"Twig_Error_Runtime",
"(",
"\"Using the eval modifier for regular expressions is not allowed\"",
")",
";",
"}",
"}"
]
| Check that the regex doesn't use the eval modifier
@param string $pattern
@throws \LogicException | [
"Check",
"that",
"the",
"regex",
"doesn",
"t",
"use",
"the",
"eval",
"modifier"
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/PcreExtension.php#L56-L64 | train |
jasny/twig-extensions | src/PcreExtension.php | PcreExtension.get | public function get($value, $pattern, $group = 0)
{
if (!isset($value)) {
return null;
}
return preg_match($pattern, $value, $matches) && isset($matches[$group]) ? $matches[$group] : null;
} | php | public function get($value, $pattern, $group = 0)
{
if (!isset($value)) {
return null;
}
return preg_match($pattern, $value, $matches) && isset($matches[$group]) ? $matches[$group] : null;
} | [
"public",
"function",
"get",
"(",
"$",
"value",
",",
"$",
"pattern",
",",
"$",
"group",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"preg_match",
"(",
"$",
"pattern",
",",
"$",
"value",
",",
"$",
"matches",
")",
"&&",
"isset",
"(",
"$",
"matches",
"[",
"$",
"group",
"]",
")",
"?",
"$",
"matches",
"[",
"$",
"group",
"]",
":",
"null",
";",
"}"
]
| Perform a regular expression match and return a matched group.
@param string $value
@param string $pattern
@return string | [
"Perform",
"a",
"regular",
"expression",
"match",
"and",
"return",
"a",
"matched",
"group",
"."
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/PcreExtension.php#L106-L113 | train |
jasny/twig-extensions | src/PcreExtension.php | PcreExtension.getAll | public function getAll($value, $pattern, $group = 0)
{
if (!isset($value)) {
return null;
}
return preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER) && isset($matches[$group])
? $matches[$group] : [];
} | php | public function getAll($value, $pattern, $group = 0)
{
if (!isset($value)) {
return null;
}
return preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER) && isset($matches[$group])
? $matches[$group] : [];
} | [
"public",
"function",
"getAll",
"(",
"$",
"value",
",",
"$",
"pattern",
",",
"$",
"group",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"preg_match_all",
"(",
"$",
"pattern",
",",
"$",
"value",
",",
"$",
"matches",
",",
"PREG_PATTERN_ORDER",
")",
"&&",
"isset",
"(",
"$",
"matches",
"[",
"$",
"group",
"]",
")",
"?",
"$",
"matches",
"[",
"$",
"group",
"]",
":",
"[",
"]",
";",
"}"
]
| Perform a regular expression match and return the group for all matches.
@param string $value
@param string $pattern
@return array | [
"Perform",
"a",
"regular",
"expression",
"match",
"and",
"return",
"the",
"group",
"for",
"all",
"matches",
"."
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/PcreExtension.php#L122-L130 | train |
jasny/twig-extensions | src/PcreExtension.php | PcreExtension.grep | public function grep($values, $pattern, $flags = '')
{
if (!isset($values)) {
return null;
}
if (is_string($flags)) {
$flags = $flags === 'invert' ? PREG_GREP_INVERT : 0;
}
return preg_grep($pattern, $values, $flags);
} | php | public function grep($values, $pattern, $flags = '')
{
if (!isset($values)) {
return null;
}
if (is_string($flags)) {
$flags = $flags === 'invert' ? PREG_GREP_INVERT : 0;
}
return preg_grep($pattern, $values, $flags);
} | [
"public",
"function",
"grep",
"(",
"$",
"values",
",",
"$",
"pattern",
",",
"$",
"flags",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"values",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"flags",
")",
")",
"{",
"$",
"flags",
"=",
"$",
"flags",
"===",
"'invert'",
"?",
"PREG_GREP_INVERT",
":",
"0",
";",
"}",
"return",
"preg_grep",
"(",
"$",
"pattern",
",",
"$",
"values",
",",
"$",
"flags",
")",
";",
"}"
]
| Perform a regular expression match and return an array of entries that match the pattern
@param array $values
@param string $pattern
@param string $flags Optional 'invert' to return entries that do not match the given pattern.
@return array | [
"Perform",
"a",
"regular",
"expression",
"match",
"and",
"return",
"an",
"array",
"of",
"entries",
"that",
"match",
"the",
"pattern"
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/PcreExtension.php#L140-L151 | train |
jasny/twig-extensions | src/TextExtension.php | TextExtension.line | public function line($value, $line = 1)
{
if (!isset($value)) {
return null;
}
$lines = explode("\n", $value);
return isset($lines[$line - 1]) ? $lines[$line - 1] : null;
} | php | public function line($value, $line = 1)
{
if (!isset($value)) {
return null;
}
$lines = explode("\n", $value);
return isset($lines[$line - 1]) ? $lines[$line - 1] : null;
} | [
"public",
"function",
"line",
"(",
"$",
"value",
",",
"$",
"line",
"=",
"1",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"lines",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"value",
")",
";",
"return",
"isset",
"(",
"$",
"lines",
"[",
"$",
"line",
"-",
"1",
"]",
")",
"?",
"$",
"lines",
"[",
"$",
"line",
"-",
"1",
"]",
":",
"null",
";",
"}"
]
| Get a single line
@param string $value
@param int $line Line number (starts at 1)
@return string | [
"Get",
"a",
"single",
"line"
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/TextExtension.php#L57-L66 | train |
jasny/twig-extensions | src/TextExtension.php | TextExtension.less | public function less($value, $replace = '...', $break = '<!-- pagebreak -->')
{
if (!isset($value)) {
return null;
}
$pos = stripos($value, $break);
return $pos === false ? $value : substr($value, 0, $pos) . $replace;
} | php | public function less($value, $replace = '...', $break = '<!-- pagebreak -->')
{
if (!isset($value)) {
return null;
}
$pos = stripos($value, $break);
return $pos === false ? $value : substr($value, 0, $pos) . $replace;
} | [
"public",
"function",
"less",
"(",
"$",
"value",
",",
"$",
"replace",
"=",
"'...'",
",",
"$",
"break",
"=",
"'<!-- pagebreak -->'",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"pos",
"=",
"stripos",
"(",
"$",
"value",
",",
"$",
"break",
")",
";",
"return",
"$",
"pos",
"===",
"false",
"?",
"$",
"value",
":",
"substr",
"(",
"$",
"value",
",",
"0",
",",
"$",
"pos",
")",
".",
"$",
"replace",
";",
"}"
]
| Cut of text on a pagebreak.
@param string $value
@param string $replace
@param string $break
@return string | [
"Cut",
"of",
"text",
"on",
"a",
"pagebreak",
"."
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/TextExtension.php#L76-L84 | train |
jasny/twig-extensions | src/TextExtension.php | TextExtension.truncate | public function truncate($value, $length, $replace = '...')
{
if (!isset($value)) {
return null;
}
return strlen($value) <= $length ? $value : substr($value, 0, $length - strlen($replace)) . $replace;
} | php | public function truncate($value, $length, $replace = '...')
{
if (!isset($value)) {
return null;
}
return strlen($value) <= $length ? $value : substr($value, 0, $length - strlen($replace)) . $replace;
} | [
"public",
"function",
"truncate",
"(",
"$",
"value",
",",
"$",
"length",
",",
"$",
"replace",
"=",
"'...'",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"strlen",
"(",
"$",
"value",
")",
"<=",
"$",
"length",
"?",
"$",
"value",
":",
"substr",
"(",
"$",
"value",
",",
"0",
",",
"$",
"length",
"-",
"strlen",
"(",
"$",
"replace",
")",
")",
".",
"$",
"replace",
";",
"}"
]
| Cut of text if it's to long.
@param string $value
@param int $length
@param string $replace
@return string | [
"Cut",
"of",
"text",
"if",
"it",
"s",
"to",
"long",
"."
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/TextExtension.php#L94-L101 | train |
jasny/twig-extensions | src/TextExtension.php | TextExtension.linkifyMail | protected function linkifyMail($text, array &$links, $attr)
{
$regexp = '~([^\s<>]+?@[^\s<>]+?\.[^\s<>]+)(?<![\.,:;\?!\'"\|])~';
return preg_replace_callback($regexp, function ($match) use (&$links, $attr) {
return '<' . array_push($links, '<a' . $attr . ' href="mailto:' . $match[1] . '">' . $match[1] . '</a>')
. '>';
}, $text);
} | php | protected function linkifyMail($text, array &$links, $attr)
{
$regexp = '~([^\s<>]+?@[^\s<>]+?\.[^\s<>]+)(?<![\.,:;\?!\'"\|])~';
return preg_replace_callback($regexp, function ($match) use (&$links, $attr) {
return '<' . array_push($links, '<a' . $attr . ' href="mailto:' . $match[1] . '">' . $match[1] . '</a>')
. '>';
}, $text);
} | [
"protected",
"function",
"linkifyMail",
"(",
"$",
"text",
",",
"array",
"&",
"$",
"links",
",",
"$",
"attr",
")",
"{",
"$",
"regexp",
"=",
"'~([^\\s<>]+?@[^\\s<>]+?\\.[^\\s<>]+)(?<![\\.,:;\\?!\\'\"\\|])~'",
";",
"return",
"preg_replace_callback",
"(",
"$",
"regexp",
",",
"function",
"(",
"$",
"match",
")",
"use",
"(",
"&",
"$",
"links",
",",
"$",
"attr",
")",
"{",
"return",
"'<'",
".",
"array_push",
"(",
"$",
"links",
",",
"'<a'",
".",
"$",
"attr",
".",
"' href=\"mailto:'",
".",
"$",
"match",
"[",
"1",
"]",
".",
"'\">'",
".",
"$",
"match",
"[",
"1",
"]",
".",
"'</a>'",
")",
".",
"'>'",
";",
"}",
",",
"$",
"text",
")",
";",
"}"
]
| Linkify a mail link.
@param string $text
@param array $links OUTPUT
@param string $attr
@return string | [
"Linkify",
"a",
"mail",
"link",
"."
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/TextExtension.php#L136-L144 | train |
jasny/twig-extensions | src/TextExtension.php | TextExtension.linkifyOther | protected function linkifyOther($protocol, $text, array &$links, $attr, $mode)
{
if (strpos($protocol, ':') === false) {
$protocol .= in_array($protocol, ['ftp', 'tftp', 'ssh', 'scp']) ? '://' : ':';
}
$regexp = $mode != 'all'
? '~' . preg_quote($protocol, '~') . '([^\s<>]+)(?<![\.,:;\?!\'"\|])~i'
: '~([^\s<>]+)(?<![\.,:])~i';
return preg_replace_callback($regexp, function ($match) use ($protocol, &$links, $attr) {
return '<' . array_push($links, '<a' . $attr . ' href="' . $protocol . $match[1] . '">' . $match[1]
. '</a>') . '>';
}, $text);
} | php | protected function linkifyOther($protocol, $text, array &$links, $attr, $mode)
{
if (strpos($protocol, ':') === false) {
$protocol .= in_array($protocol, ['ftp', 'tftp', 'ssh', 'scp']) ? '://' : ':';
}
$regexp = $mode != 'all'
? '~' . preg_quote($protocol, '~') . '([^\s<>]+)(?<![\.,:;\?!\'"\|])~i'
: '~([^\s<>]+)(?<![\.,:])~i';
return preg_replace_callback($regexp, function ($match) use ($protocol, &$links, $attr) {
return '<' . array_push($links, '<a' . $attr . ' href="' . $protocol . $match[1] . '">' . $match[1]
. '</a>') . '>';
}, $text);
} | [
"protected",
"function",
"linkifyOther",
"(",
"$",
"protocol",
",",
"$",
"text",
",",
"array",
"&",
"$",
"links",
",",
"$",
"attr",
",",
"$",
"mode",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"protocol",
",",
"':'",
")",
"===",
"false",
")",
"{",
"$",
"protocol",
".=",
"in_array",
"(",
"$",
"protocol",
",",
"[",
"'ftp'",
",",
"'tftp'",
",",
"'ssh'",
",",
"'scp'",
"]",
")",
"?",
"'://'",
":",
"':'",
";",
"}",
"$",
"regexp",
"=",
"$",
"mode",
"!=",
"'all'",
"?",
"'~'",
".",
"preg_quote",
"(",
"$",
"protocol",
",",
"'~'",
")",
".",
"'([^\\s<>]+)(?<![\\.,:;\\?!\\'\"\\|])~i'",
":",
"'~([^\\s<>]+)(?<![\\.,:])~i'",
";",
"return",
"preg_replace_callback",
"(",
"$",
"regexp",
",",
"function",
"(",
"$",
"match",
")",
"use",
"(",
"$",
"protocol",
",",
"&",
"$",
"links",
",",
"$",
"attr",
")",
"{",
"return",
"'<'",
".",
"array_push",
"(",
"$",
"links",
",",
"'<a'",
".",
"$",
"attr",
".",
"' href=\"'",
".",
"$",
"protocol",
".",
"$",
"match",
"[",
"1",
"]",
".",
"'\">'",
".",
"$",
"match",
"[",
"1",
"]",
".",
"'</a>'",
")",
".",
"'>'",
";",
"}",
",",
"$",
"text",
")",
";",
"}"
]
| Linkify a link.
@param string $protocol
@param string $text
@param array $links OUTPUT
@param string $attr
@param string $mode
@return string | [
"Linkify",
"a",
"link",
"."
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/TextExtension.php#L157-L171 | train |
jasny/twig-extensions | src/TextExtension.php | TextExtension.linkify | public function linkify($value, $protocols = ['http', 'mail'], array $attributes = [], $mode = 'normal')
{
if (!isset($value)) {
return null;
}
// Link attributes
$attr = '';
foreach ($attributes as $key => $val) {
$attr .= ' ' . $key . '="' . htmlentities($val) . '"';
}
$links = [];
// Extract existing links and tags
$text = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i', function ($match) use (&$links) {
return '<' . array_push($links, $match[1]) . '>';
}, $value);
// Extract text links for each protocol
foreach ((array)$protocols as $protocol) {
switch ($protocol) {
case 'http':
case 'https': $text = $this->linkifyHttp($protocol, $text, $links, $attr, $mode); break;
case 'mail': $text = $this->linkifyMail($text, $links, $attr); break;
default: $text = $this->linkifyOther($protocol, $text, $links, $attr, $mode); break;
}
}
// Insert all link
return preg_replace_callback('/<(\d+)>/', function ($match) use (&$links) {
return $links[$match[1] - 1];
}, $text);
} | php | public function linkify($value, $protocols = ['http', 'mail'], array $attributes = [], $mode = 'normal')
{
if (!isset($value)) {
return null;
}
// Link attributes
$attr = '';
foreach ($attributes as $key => $val) {
$attr .= ' ' . $key . '="' . htmlentities($val) . '"';
}
$links = [];
// Extract existing links and tags
$text = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i', function ($match) use (&$links) {
return '<' . array_push($links, $match[1]) . '>';
}, $value);
// Extract text links for each protocol
foreach ((array)$protocols as $protocol) {
switch ($protocol) {
case 'http':
case 'https': $text = $this->linkifyHttp($protocol, $text, $links, $attr, $mode); break;
case 'mail': $text = $this->linkifyMail($text, $links, $attr); break;
default: $text = $this->linkifyOther($protocol, $text, $links, $attr, $mode); break;
}
}
// Insert all link
return preg_replace_callback('/<(\d+)>/', function ($match) use (&$links) {
return $links[$match[1] - 1];
}, $text);
} | [
"public",
"function",
"linkify",
"(",
"$",
"value",
",",
"$",
"protocols",
"=",
"[",
"'http'",
",",
"'mail'",
"]",
",",
"array",
"$",
"attributes",
"=",
"[",
"]",
",",
"$",
"mode",
"=",
"'normal'",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"// Link attributes",
"$",
"attr",
"=",
"''",
";",
"foreach",
"(",
"$",
"attributes",
"as",
"$",
"key",
"=>",
"$",
"val",
")",
"{",
"$",
"attr",
".=",
"' '",
".",
"$",
"key",
".",
"'=\"'",
".",
"htmlentities",
"(",
"$",
"val",
")",
".",
"'\"'",
";",
"}",
"$",
"links",
"=",
"[",
"]",
";",
"// Extract existing links and tags",
"$",
"text",
"=",
"preg_replace_callback",
"(",
"'~(<a .*?>.*?</a>|<.*?>)~i'",
",",
"function",
"(",
"$",
"match",
")",
"use",
"(",
"&",
"$",
"links",
")",
"{",
"return",
"'<'",
".",
"array_push",
"(",
"$",
"links",
",",
"$",
"match",
"[",
"1",
"]",
")",
".",
"'>'",
";",
"}",
",",
"$",
"value",
")",
";",
"// Extract text links for each protocol",
"foreach",
"(",
"(",
"array",
")",
"$",
"protocols",
"as",
"$",
"protocol",
")",
"{",
"switch",
"(",
"$",
"protocol",
")",
"{",
"case",
"'http'",
":",
"case",
"'https'",
":",
"$",
"text",
"=",
"$",
"this",
"->",
"linkifyHttp",
"(",
"$",
"protocol",
",",
"$",
"text",
",",
"$",
"links",
",",
"$",
"attr",
",",
"$",
"mode",
")",
";",
"break",
";",
"case",
"'mail'",
":",
"$",
"text",
"=",
"$",
"this",
"->",
"linkifyMail",
"(",
"$",
"text",
",",
"$",
"links",
",",
"$",
"attr",
")",
";",
"break",
";",
"default",
":",
"$",
"text",
"=",
"$",
"this",
"->",
"linkifyOther",
"(",
"$",
"protocol",
",",
"$",
"text",
",",
"$",
"links",
",",
"$",
"attr",
",",
"$",
"mode",
")",
";",
"break",
";",
"}",
"}",
"// Insert all link",
"return",
"preg_replace_callback",
"(",
"'/<(\\d+)>/'",
",",
"function",
"(",
"$",
"match",
")",
"use",
"(",
"&",
"$",
"links",
")",
"{",
"return",
"$",
"links",
"[",
"$",
"match",
"[",
"1",
"]",
"-",
"1",
"]",
";",
"}",
",",
"$",
"text",
")",
";",
"}"
]
| Turn all URLs in clickable links.
@param string $value
@param array $protocols 'http'/'https', 'mail' and also 'ftp', 'scp', 'tel', etc
@param array $attributes HTML attributes for the link
@param string $mode normal or all
@return string | [
"Turn",
"all",
"URLs",
"in",
"clickable",
"links",
"."
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/TextExtension.php#L182-L215 | train |
jasny/twig-extensions | src/ArrayExtension.php | ArrayExtension.htmlAttributes | public function htmlAttributes($array)
{
if (!isset($array)) {
return null;
}
$str = "";
foreach ($array as $key => $value) {
if (!isset($value) || $value === false) {
continue;
}
if ($value === true) {
$value = $key;
}
$str .= ' ' . $key . '="' . addcslashes($value, '"') . '"';
}
return trim($str);
} | php | public function htmlAttributes($array)
{
if (!isset($array)) {
return null;
}
$str = "";
foreach ($array as $key => $value) {
if (!isset($value) || $value === false) {
continue;
}
if ($value === true) {
$value = $key;
}
$str .= ' ' . $key . '="' . addcslashes($value, '"') . '"';
}
return trim($str);
} | [
"public",
"function",
"htmlAttributes",
"(",
"$",
"array",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"array",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"str",
"=",
"\"\"",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
")",
"||",
"$",
"value",
"===",
"false",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"value",
"===",
"true",
")",
"{",
"$",
"value",
"=",
"$",
"key",
";",
"}",
"$",
"str",
".=",
"' '",
".",
"$",
"key",
".",
"'=\"'",
".",
"addcslashes",
"(",
"$",
"value",
",",
"'\"'",
")",
".",
"'\"'",
";",
"}",
"return",
"trim",
"(",
"$",
"str",
")",
";",
"}"
]
| Cast an array to an HTML attribute string
@param mixed $array
@return string | [
"Cast",
"an",
"array",
"to",
"an",
"HTML",
"attribute",
"string"
]
| 30bdf3a3903c021544f36332c9d5d4d563527da4 | https://github.com/jasny/twig-extensions/blob/30bdf3a3903c021544f36332c9d5d4d563527da4/src/ArrayExtension.php#L86-L106 | train |
Komtet/komtet-kassa-php-sdk | src/QueueManager.php | QueueManager.setDefaultQueue | public function setDefaultQueue($name)
{
if (!$this->hasQueue($name)) {
throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $name));
}
$this->defaultQueue = $name;
return $this;
} | php | public function setDefaultQueue($name)
{
if (!$this->hasQueue($name)) {
throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $name));
}
$this->defaultQueue = $name;
return $this;
} | [
"public",
"function",
"setDefaultQueue",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasQueue",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Unknown queue \"%s\"'",
",",
"$",
"name",
")",
")",
";",
"}",
"$",
"this",
"->",
"defaultQueue",
"=",
"$",
"name",
";",
"return",
"$",
"this",
";",
"}"
]
| Sets default queue
@param string $name Queue name
@return QueueManager | [
"Sets",
"default",
"queue"
]
| 0d87098c2e7b1ac2d095dcbf5f1866a84b667288 | https://github.com/Komtet/komtet-kassa-php-sdk/blob/0d87098c2e7b1ac2d095dcbf5f1866a84b667288/src/QueueManager.php#L59-L68 | train |
Komtet/komtet-kassa-php-sdk | src/QueueManager.php | QueueManager.putCheck | public function putCheck($check, $queueName = null)
{
if ($queueName === null) {
if ($this->defaultQueue === null) {
throw new \LogicException('Default queue is not set');
}
$queueName = $this->defaultQueue;
}
if (!$this->hasQueue($queueName)) {
throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $queueName));
}
$path = sprintf('api/shop/v1/queues/%s/task', $this->queues[$queueName]);
return $this->client->sendRequest($path, $check->asArray());
} | php | public function putCheck($check, $queueName = null)
{
if ($queueName === null) {
if ($this->defaultQueue === null) {
throw new \LogicException('Default queue is not set');
}
$queueName = $this->defaultQueue;
}
if (!$this->hasQueue($queueName)) {
throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $queueName));
}
$path = sprintf('api/shop/v1/queues/%s/task', $this->queues[$queueName]);
return $this->client->sendRequest($path, $check->asArray());
} | [
"public",
"function",
"putCheck",
"(",
"$",
"check",
",",
"$",
"queueName",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"queueName",
"===",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"defaultQueue",
"===",
"null",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'Default queue is not set'",
")",
";",
"}",
"$",
"queueName",
"=",
"$",
"this",
"->",
"defaultQueue",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"hasQueue",
"(",
"$",
"queueName",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Unknown queue \"%s\"'",
",",
"$",
"queueName",
")",
")",
";",
"}",
"$",
"path",
"=",
"sprintf",
"(",
"'api/shop/v1/queues/%s/task'",
",",
"$",
"this",
"->",
"queues",
"[",
"$",
"queueName",
"]",
")",
";",
"return",
"$",
"this",
"->",
"client",
"->",
"sendRequest",
"(",
"$",
"path",
",",
"$",
"check",
"->",
"asArray",
"(",
")",
")",
";",
"}"
]
| Sends a check to queue
@param Check|CorrectionCheck $check Check instance
@param string $queueName Queue name
@return mixed | [
"Sends",
"a",
"check",
"to",
"queue"
]
| 0d87098c2e7b1ac2d095dcbf5f1866a84b667288 | https://github.com/Komtet/komtet-kassa-php-sdk/blob/0d87098c2e7b1ac2d095dcbf5f1866a84b667288/src/QueueManager.php#L90-L105 | train |
Komtet/komtet-kassa-php-sdk | src/QueueManager.php | QueueManager.isQueueActive | public function isQueueActive($name)
{
if (!$this->hasQueue($name)) {
throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $name));
}
$path = sprintf('api/shop/v1/queues/%s', $this->queues[$name]);
$data = $this->client->sendRequest($path);
return is_array($data) && array_key_exists('state', $data) ? $data['state'] == 'active' : false;
} | php | public function isQueueActive($name)
{
if (!$this->hasQueue($name)) {
throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $name));
}
$path = sprintf('api/shop/v1/queues/%s', $this->queues[$name]);
$data = $this->client->sendRequest($path);
return is_array($data) && array_key_exists('state', $data) ? $data['state'] == 'active' : false;
} | [
"public",
"function",
"isQueueActive",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasQueue",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Unknown queue \"%s\"'",
",",
"$",
"name",
")",
")",
";",
"}",
"$",
"path",
"=",
"sprintf",
"(",
"'api/shop/v1/queues/%s'",
",",
"$",
"this",
"->",
"queues",
"[",
"$",
"name",
"]",
")",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"client",
"->",
"sendRequest",
"(",
"$",
"path",
")",
";",
"return",
"is_array",
"(",
"$",
"data",
")",
"&&",
"array_key_exists",
"(",
"'state'",
",",
"$",
"data",
")",
"?",
"$",
"data",
"[",
"'state'",
"]",
"==",
"'active'",
":",
"false",
";",
"}"
]
| Whether queue active
@param string $name Queue name
@return bool | [
"Whether",
"queue",
"active"
]
| 0d87098c2e7b1ac2d095dcbf5f1866a84b667288 | https://github.com/Komtet/komtet-kassa-php-sdk/blob/0d87098c2e7b1ac2d095dcbf5f1866a84b667288/src/QueueManager.php#L114-L122 | train |
bummzack/sortablefile | src/Forms/SortableUploadField.php | SortableUploadField.getItems | public function getItems()
{
$items = parent::getItems();
// An ArrayList won't contain our sort-column, thus it has to be sorted by the raw submittal data.
// This is an issue that's seemingly exclusive to saving SiteConfig.
if (($items instanceof ArrayList) && !empty($this->rawSubmittal)) {
// flip the array, so that we can look up index by ID
$sortLookup = array_flip($this->rawSubmittal);
$itemsArray = $items->toArray();
usort($itemsArray, function ($itemA, $itemB) use ($sortLookup) {
if (isset($sortLookup[$itemA->ID]) && isset($sortLookup[$itemB->ID])) {
return $sortLookup[$itemA->ID] - $sortLookup[$itemB->ID];
}
return 0;
});
return ArrayList::create($itemsArray);
}
if ($items instanceof Sortable) {
return $items->sort([$this->getSortColumn() => 'ASC', 'ID' => 'ASC']);
}
return $items;
} | php | public function getItems()
{
$items = parent::getItems();
// An ArrayList won't contain our sort-column, thus it has to be sorted by the raw submittal data.
// This is an issue that's seemingly exclusive to saving SiteConfig.
if (($items instanceof ArrayList) && !empty($this->rawSubmittal)) {
// flip the array, so that we can look up index by ID
$sortLookup = array_flip($this->rawSubmittal);
$itemsArray = $items->toArray();
usort($itemsArray, function ($itemA, $itemB) use ($sortLookup) {
if (isset($sortLookup[$itemA->ID]) && isset($sortLookup[$itemB->ID])) {
return $sortLookup[$itemA->ID] - $sortLookup[$itemB->ID];
}
return 0;
});
return ArrayList::create($itemsArray);
}
if ($items instanceof Sortable) {
return $items->sort([$this->getSortColumn() => 'ASC', 'ID' => 'ASC']);
}
return $items;
} | [
"public",
"function",
"getItems",
"(",
")",
"{",
"$",
"items",
"=",
"parent",
"::",
"getItems",
"(",
")",
";",
"// An ArrayList won't contain our sort-column, thus it has to be sorted by the raw submittal data.",
"// This is an issue that's seemingly exclusive to saving SiteConfig.",
"if",
"(",
"(",
"$",
"items",
"instanceof",
"ArrayList",
")",
"&&",
"!",
"empty",
"(",
"$",
"this",
"->",
"rawSubmittal",
")",
")",
"{",
"// flip the array, so that we can look up index by ID",
"$",
"sortLookup",
"=",
"array_flip",
"(",
"$",
"this",
"->",
"rawSubmittal",
")",
";",
"$",
"itemsArray",
"=",
"$",
"items",
"->",
"toArray",
"(",
")",
";",
"usort",
"(",
"$",
"itemsArray",
",",
"function",
"(",
"$",
"itemA",
",",
"$",
"itemB",
")",
"use",
"(",
"$",
"sortLookup",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"sortLookup",
"[",
"$",
"itemA",
"->",
"ID",
"]",
")",
"&&",
"isset",
"(",
"$",
"sortLookup",
"[",
"$",
"itemB",
"->",
"ID",
"]",
")",
")",
"{",
"return",
"$",
"sortLookup",
"[",
"$",
"itemA",
"->",
"ID",
"]",
"-",
"$",
"sortLookup",
"[",
"$",
"itemB",
"->",
"ID",
"]",
";",
"}",
"return",
"0",
";",
"}",
")",
";",
"return",
"ArrayList",
"::",
"create",
"(",
"$",
"itemsArray",
")",
";",
"}",
"if",
"(",
"$",
"items",
"instanceof",
"Sortable",
")",
"{",
"return",
"$",
"items",
"->",
"sort",
"(",
"[",
"$",
"this",
"->",
"getSortColumn",
"(",
")",
"=>",
"'ASC'",
",",
"'ID'",
"=>",
"'ASC'",
"]",
")",
";",
"}",
"return",
"$",
"items",
";",
"}"
]
| Return the files in sorted order
@return File[]|SS_List | [
"Return",
"the",
"files",
"in",
"sorted",
"order"
]
| 0028923180b10d7613ff239a0fd56acdf96872ab | https://github.com/bummzack/sortablefile/blob/0028923180b10d7613ff239a0fd56acdf96872ab/src/Forms/SortableUploadField.php#L81-L106 | train |
bummzack/sortablefile | src/Forms/SortableUploadField.php | SortableUploadField.sortManyManyRelation | protected function sortManyManyRelation(
ManyManyList $relation,
array $idList,
array $rawList,
DataObjectInterface $record,
$sortColumn
) {
$relation->getForeignID();
$ownerIdField = $relation->getForeignKey();
$fileIdField = $relation->getLocalKey();
$joinTable = '"' . $relation->getJoinTable() . '"';
$sort = 0;
foreach ($rawList as $id) {
if (in_array($id, $idList)) {
// Use SQLUpdate to update the data in the join-table.
// This is safe to do, since new records have already been written to the DB in the
// parent::saveInto call.
SQLUpdate::create($joinTable)
->setWhere([
"\"$ownerIdField\" = ?" => $record->ID,
"\"$fileIdField\" = ?" => $id
])
->assign($sortColumn, $sort++)
->execute();
}
}
} | php | protected function sortManyManyRelation(
ManyManyList $relation,
array $idList,
array $rawList,
DataObjectInterface $record,
$sortColumn
) {
$relation->getForeignID();
$ownerIdField = $relation->getForeignKey();
$fileIdField = $relation->getLocalKey();
$joinTable = '"' . $relation->getJoinTable() . '"';
$sort = 0;
foreach ($rawList as $id) {
if (in_array($id, $idList)) {
// Use SQLUpdate to update the data in the join-table.
// This is safe to do, since new records have already been written to the DB in the
// parent::saveInto call.
SQLUpdate::create($joinTable)
->setWhere([
"\"$ownerIdField\" = ?" => $record->ID,
"\"$fileIdField\" = ?" => $id
])
->assign($sortColumn, $sort++)
->execute();
}
}
} | [
"protected",
"function",
"sortManyManyRelation",
"(",
"ManyManyList",
"$",
"relation",
",",
"array",
"$",
"idList",
",",
"array",
"$",
"rawList",
",",
"DataObjectInterface",
"$",
"record",
",",
"$",
"sortColumn",
")",
"{",
"$",
"relation",
"->",
"getForeignID",
"(",
")",
";",
"$",
"ownerIdField",
"=",
"$",
"relation",
"->",
"getForeignKey",
"(",
")",
";",
"$",
"fileIdField",
"=",
"$",
"relation",
"->",
"getLocalKey",
"(",
")",
";",
"$",
"joinTable",
"=",
"'\"'",
".",
"$",
"relation",
"->",
"getJoinTable",
"(",
")",
".",
"'\"'",
";",
"$",
"sort",
"=",
"0",
";",
"foreach",
"(",
"$",
"rawList",
"as",
"$",
"id",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"id",
",",
"$",
"idList",
")",
")",
"{",
"// Use SQLUpdate to update the data in the join-table.",
"// This is safe to do, since new records have already been written to the DB in the",
"// parent::saveInto call.",
"SQLUpdate",
"::",
"create",
"(",
"$",
"joinTable",
")",
"->",
"setWhere",
"(",
"[",
"\"\\\"$ownerIdField\\\" = ?\"",
"=>",
"$",
"record",
"->",
"ID",
",",
"\"\\\"$fileIdField\\\" = ?\"",
"=>",
"$",
"id",
"]",
")",
"->",
"assign",
"(",
"$",
"sortColumn",
",",
"$",
"sort",
"++",
")",
"->",
"execute",
"(",
")",
";",
"}",
"}",
"}"
]
| Apply sorting to a many_many relation
@param ManyManyList $relation
@param array $idList
@param array $rawList
@param DataObjectInterface $record
@param $sortColumn | [
"Apply",
"sorting",
"to",
"a",
"many_many",
"relation"
]
| 0028923180b10d7613ff239a0fd56acdf96872ab | https://github.com/bummzack/sortablefile/blob/0028923180b10d7613ff239a0fd56acdf96872ab/src/Forms/SortableUploadField.php#L177-L203 | train |
bummzack/sortablefile | src/Forms/SortableUploadField.php | SortableUploadField.sortManyManyThroughRelation | protected function sortManyManyThroughRelation(
ManyManyThroughList $relation,
array $idList,
array $rawList,
$sortColumn
) {
$relation->getForeignID();
$dataQuery = $relation->dataQuery();
$manipulators = $dataQuery->getDataQueryManipulators();
$manyManyManipulator = null;
foreach ($manipulators as $manipulator) {
if ($manipulator instanceof ManyManyThroughQueryManipulator) {
$manyManyManipulator = $manipulator;
break;
}
}
if (!$manyManyManipulator) {
throw new \LogicException('No ManyManyThroughQueryManipulator found');
}
$joinClass = $manyManyManipulator->getJoinClass();
$ownerIDField = $manyManyManipulator->getForeignKey();
$fileIdField = $manyManyManipulator->getLocalKey();
$sort = 0;
foreach ($rawList as $id) {
if (in_array($id, $idList)) {
$fileRecord = DataList::create($joinClass)->filter([
$ownerIDField => $relation->getForeignID(),
$fileIdField => $id
])->first();
if ($fileRecord) {
$fileRecord->setField($sortColumn, $sort++);
$fileRecord->write();
}
}
}
} | php | protected function sortManyManyThroughRelation(
ManyManyThroughList $relation,
array $idList,
array $rawList,
$sortColumn
) {
$relation->getForeignID();
$dataQuery = $relation->dataQuery();
$manipulators = $dataQuery->getDataQueryManipulators();
$manyManyManipulator = null;
foreach ($manipulators as $manipulator) {
if ($manipulator instanceof ManyManyThroughQueryManipulator) {
$manyManyManipulator = $manipulator;
break;
}
}
if (!$manyManyManipulator) {
throw new \LogicException('No ManyManyThroughQueryManipulator found');
}
$joinClass = $manyManyManipulator->getJoinClass();
$ownerIDField = $manyManyManipulator->getForeignKey();
$fileIdField = $manyManyManipulator->getLocalKey();
$sort = 0;
foreach ($rawList as $id) {
if (in_array($id, $idList)) {
$fileRecord = DataList::create($joinClass)->filter([
$ownerIDField => $relation->getForeignID(),
$fileIdField => $id
])->first();
if ($fileRecord) {
$fileRecord->setField($sortColumn, $sort++);
$fileRecord->write();
}
}
}
} | [
"protected",
"function",
"sortManyManyThroughRelation",
"(",
"ManyManyThroughList",
"$",
"relation",
",",
"array",
"$",
"idList",
",",
"array",
"$",
"rawList",
",",
"$",
"sortColumn",
")",
"{",
"$",
"relation",
"->",
"getForeignID",
"(",
")",
";",
"$",
"dataQuery",
"=",
"$",
"relation",
"->",
"dataQuery",
"(",
")",
";",
"$",
"manipulators",
"=",
"$",
"dataQuery",
"->",
"getDataQueryManipulators",
"(",
")",
";",
"$",
"manyManyManipulator",
"=",
"null",
";",
"foreach",
"(",
"$",
"manipulators",
"as",
"$",
"manipulator",
")",
"{",
"if",
"(",
"$",
"manipulator",
"instanceof",
"ManyManyThroughQueryManipulator",
")",
"{",
"$",
"manyManyManipulator",
"=",
"$",
"manipulator",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"$",
"manyManyManipulator",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'No ManyManyThroughQueryManipulator found'",
")",
";",
"}",
"$",
"joinClass",
"=",
"$",
"manyManyManipulator",
"->",
"getJoinClass",
"(",
")",
";",
"$",
"ownerIDField",
"=",
"$",
"manyManyManipulator",
"->",
"getForeignKey",
"(",
")",
";",
"$",
"fileIdField",
"=",
"$",
"manyManyManipulator",
"->",
"getLocalKey",
"(",
")",
";",
"$",
"sort",
"=",
"0",
";",
"foreach",
"(",
"$",
"rawList",
"as",
"$",
"id",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"id",
",",
"$",
"idList",
")",
")",
"{",
"$",
"fileRecord",
"=",
"DataList",
"::",
"create",
"(",
"$",
"joinClass",
")",
"->",
"filter",
"(",
"[",
"$",
"ownerIDField",
"=>",
"$",
"relation",
"->",
"getForeignID",
"(",
")",
",",
"$",
"fileIdField",
"=>",
"$",
"id",
"]",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"$",
"fileRecord",
")",
"{",
"$",
"fileRecord",
"->",
"setField",
"(",
"$",
"sortColumn",
",",
"$",
"sort",
"++",
")",
";",
"$",
"fileRecord",
"->",
"write",
"(",
")",
";",
"}",
"}",
"}",
"}"
]
| Apply sorting to a many_many_through relation
@param ManyManyThroughList $relation
@param array $idList
@param array $rawList
@param $sortColumn
@throws \SilverStripe\ORM\ValidationException | [
"Apply",
"sorting",
"to",
"a",
"many_many_through",
"relation"
]
| 0028923180b10d7613ff239a0fd56acdf96872ab | https://github.com/bummzack/sortablefile/blob/0028923180b10d7613ff239a0fd56acdf96872ab/src/Forms/SortableUploadField.php#L213-L252 | train |
hhvm/hhvm-autoload | src/ComposerPlugin.php | ComposerPlugin.onPostAutoloadDump | public function onPostAutoloadDump(Event $event) {
$args = $event->isDevMode() ? '' : ' --no-dev';
$finder = new ExecutableFinder();
$hhvm = $finder->find('hhvm', 'hhvm');
$executor = new ProcessExecutor($this->io);
$command = $hhvm . ' ' . ProcessExecutor::escape($this->vendor.'/bin/hh-autoload.hack') . $args;
$executor->execute($command);
} | php | public function onPostAutoloadDump(Event $event) {
$args = $event->isDevMode() ? '' : ' --no-dev';
$finder = new ExecutableFinder();
$hhvm = $finder->find('hhvm', 'hhvm');
$executor = new ProcessExecutor($this->io);
$command = $hhvm . ' ' . ProcessExecutor::escape($this->vendor.'/bin/hh-autoload.hack') . $args;
$executor->execute($command);
} | [
"public",
"function",
"onPostAutoloadDump",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"args",
"=",
"$",
"event",
"->",
"isDevMode",
"(",
")",
"?",
"''",
":",
"' --no-dev'",
";",
"$",
"finder",
"=",
"new",
"ExecutableFinder",
"(",
")",
";",
"$",
"hhvm",
"=",
"$",
"finder",
"->",
"find",
"(",
"'hhvm'",
",",
"'hhvm'",
")",
";",
"$",
"executor",
"=",
"new",
"ProcessExecutor",
"(",
"$",
"this",
"->",
"io",
")",
";",
"$",
"command",
"=",
"$",
"hhvm",
".",
"' '",
".",
"ProcessExecutor",
"::",
"escape",
"(",
"$",
"this",
"->",
"vendor",
".",
"'/bin/hh-autoload.hack'",
")",
".",
"$",
"args",
";",
"$",
"executor",
"->",
"execute",
"(",
"$",
"command",
")",
";",
"}"
]
| Callback for after the main composer autoload map has been updated.
Here we update our autoload map. | [
"Callback",
"for",
"after",
"the",
"main",
"composer",
"autoload",
"map",
"has",
"been",
"updated",
"."
]
| f8bde26ced3ad182a4e9138c95e077ca47b37e22 | https://github.com/hhvm/hhvm-autoload/blob/f8bde26ced3ad182a4e9138c95e077ca47b37e22/src/ComposerPlugin.php#L61-L68 | train |
bhaktaraz/php-rss-generator | Source/Bhaktaraz/RSSGenerator/SimpleXMLElement.php | SimpleXMLElement.addChildCData | public function addChildCData($name, $cdata_text)
{
$child = $this->addChild($name);
$child->addCData($cdata_text);
} | php | public function addChildCData($name, $cdata_text)
{
$child = $this->addChild($name);
$child->addCData($cdata_text);
} | [
"public",
"function",
"addChildCData",
"(",
"$",
"name",
",",
"$",
"cdata_text",
")",
"{",
"$",
"child",
"=",
"$",
"this",
"->",
"addChild",
"(",
"$",
"name",
")",
";",
"$",
"child",
"->",
"addCData",
"(",
"$",
"cdata_text",
")",
";",
"}"
]
| Create a child with CDATA value
@param string $name The name of the child element to add.
@param string $cdata_text The CDATA value of the child element. | [
"Create",
"a",
"child",
"with",
"CDATA",
"value"
]
| 4c90e6e2fbb74f0dcb3cf6d1fcd4fa1a77b53f0d | https://github.com/bhaktaraz/php-rss-generator/blob/4c90e6e2fbb74f0dcb3cf6d1fcd4fa1a77b53f0d/Source/Bhaktaraz/RSSGenerator/SimpleXMLElement.php#L30-L34 | train |
pomm-project/Foundation | sources/lib/Inflector.php | Inflector.underscore | public static function underscore($string = null)
{
if ($string === null) {
return null;
}
return strtolower(preg_replace('/([A-Z])/', '_\1', lcfirst($string)));
} | php | public static function underscore($string = null)
{
if ($string === null) {
return null;
}
return strtolower(preg_replace('/([A-Z])/', '_\1', lcfirst($string)));
} | [
"public",
"static",
"function",
"underscore",
"(",
"$",
"string",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"string",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"strtolower",
"(",
"preg_replace",
"(",
"'/([A-Z])/'",
",",
"'_\\1'",
",",
"lcfirst",
"(",
"$",
"string",
")",
")",
")",
";",
"}"
]
| Underscore a string.
@param string $string
@return string | [
"Underscore",
"a",
"string",
"."
]
| 34244acffa50b4a6ccd77cb96133dc38e410c914 | https://github.com/pomm-project/Foundation/blob/34244acffa50b4a6ccd77cb96133dc38e410c914/sources/lib/Inflector.php#L51-L58 | train |
verbb/cp-nav | src/services/CpNavService.php | CpNavService.setupDefaults | public function setupDefaults($layoutId = 1)
{
$layoutService = CpNav::$plugin->layoutService;
$navigationService = CpNav::$plugin->navigationService;
if (!$layoutService->getById($layoutId)) {
$layoutService->setDefaultLayout($layoutId);
}
// Populate navs with 'stock' navigation
$navService = new Cp();
$defaultNavs = $navService->nav();
foreach ($defaultNavs as $nav) {
$key = strtolower($nav['label']);
if (!$navigationService->getByHandle($layoutId, $key)) {
// Handleball off to the main menu regeneration function - no need to duplicate code
$this->regenerateNav($layoutId, [], $defaultNavs);
}
}
} | php | public function setupDefaults($layoutId = 1)
{
$layoutService = CpNav::$plugin->layoutService;
$navigationService = CpNav::$plugin->navigationService;
if (!$layoutService->getById($layoutId)) {
$layoutService->setDefaultLayout($layoutId);
}
// Populate navs with 'stock' navigation
$navService = new Cp();
$defaultNavs = $navService->nav();
foreach ($defaultNavs as $nav) {
$key = strtolower($nav['label']);
if (!$navigationService->getByHandle($layoutId, $key)) {
// Handleball off to the main menu regeneration function - no need to duplicate code
$this->regenerateNav($layoutId, [], $defaultNavs);
}
}
} | [
"public",
"function",
"setupDefaults",
"(",
"$",
"layoutId",
"=",
"1",
")",
"{",
"$",
"layoutService",
"=",
"CpNav",
"::",
"$",
"plugin",
"->",
"layoutService",
";",
"$",
"navigationService",
"=",
"CpNav",
"::",
"$",
"plugin",
"->",
"navigationService",
";",
"if",
"(",
"!",
"$",
"layoutService",
"->",
"getById",
"(",
"$",
"layoutId",
")",
")",
"{",
"$",
"layoutService",
"->",
"setDefaultLayout",
"(",
"$",
"layoutId",
")",
";",
"}",
"// Populate navs with 'stock' navigation",
"$",
"navService",
"=",
"new",
"Cp",
"(",
")",
";",
"$",
"defaultNavs",
"=",
"$",
"navService",
"->",
"nav",
"(",
")",
";",
"foreach",
"(",
"$",
"defaultNavs",
"as",
"$",
"nav",
")",
"{",
"$",
"key",
"=",
"strtolower",
"(",
"$",
"nav",
"[",
"'label'",
"]",
")",
";",
"if",
"(",
"!",
"$",
"navigationService",
"->",
"getByHandle",
"(",
"$",
"layoutId",
",",
"$",
"key",
")",
")",
"{",
"// Handleball off to the main menu regeneration function - no need to duplicate code",
"$",
"this",
"->",
"regenerateNav",
"(",
"$",
"layoutId",
",",
"[",
"]",
",",
"$",
"defaultNavs",
")",
";",
"}",
"}",
"}"
]
| Create the default Layout after plugin is installed
@param integer $layoutId | [
"Create",
"the",
"default",
"Layout",
"after",
"plugin",
"is",
"installed"
]
| 04d258fa8a92fddb895a44b5c49cad9eabf256a3 | https://github.com/verbb/cp-nav/blob/04d258fa8a92fddb895a44b5c49cad9eabf256a3/src/services/CpNavService.php#L129-L151 | train |
verbb/cp-nav | src/services/CpNavService.php | CpNavService.regenerateNav | public function regenerateNav($layoutId, $generatedNav, $currentNav)
{
// Find the extra or missing menu item
if (count($generatedNav) < count($currentNav)) {
$order = 0;
// A menu item exists in the menu, but not in our records - add
foreach ($currentNav as $value) {
if (isset($value['url'])) {
$handle = str_replace(UrlHelper::url() . '/', '', $value['url']);
} else {
$handle = StringHelper::toKebabCase($value['label']);
}
if (!isset($generatedNav[$handle]) && !CpNav::$plugin->navigationService->getByHandle($layoutId, $handle)) {
$icon = null;
// Check for custom icon (plugins)
if (isset($value['icon'])) {
$icon = $value['icon'];
}
// Check for built-in Craft icon
if (isset($value['fontIcon'])) {
$icon = $value['fontIcon'];
}
$model = $this->_prepareNavModel([
'layoutId' => $layoutId,
'handle' => $handle,
'label' => $value['label'],
'order' => $order,
'icon' => $icon,
'url' => $handle,
]);
CpNav::$plugin->navigationService->save($model);
}
$order++;
}
} else {
// Create an array of current navigation handles to easy check via in_array
$currentNavHandles = array_column($currentNav, 'url');
// A menu item exists in our records, but not in the menu - delete
foreach ($generatedNav as $key => $value) {
if (!\in_array($value['handle'], $currentNavHandles, false)) {
$navModel = CpNav::$plugin->navigationService->getByHandle($layoutId, $value['handle']);
if ($navModel) {
CpNav::$plugin->navigationService->delete($navModel);
}
}
}
}
} | php | public function regenerateNav($layoutId, $generatedNav, $currentNav)
{
// Find the extra or missing menu item
if (count($generatedNav) < count($currentNav)) {
$order = 0;
// A menu item exists in the menu, but not in our records - add
foreach ($currentNav as $value) {
if (isset($value['url'])) {
$handle = str_replace(UrlHelper::url() . '/', '', $value['url']);
} else {
$handle = StringHelper::toKebabCase($value['label']);
}
if (!isset($generatedNav[$handle]) && !CpNav::$plugin->navigationService->getByHandle($layoutId, $handle)) {
$icon = null;
// Check for custom icon (plugins)
if (isset($value['icon'])) {
$icon = $value['icon'];
}
// Check for built-in Craft icon
if (isset($value['fontIcon'])) {
$icon = $value['fontIcon'];
}
$model = $this->_prepareNavModel([
'layoutId' => $layoutId,
'handle' => $handle,
'label' => $value['label'],
'order' => $order,
'icon' => $icon,
'url' => $handle,
]);
CpNav::$plugin->navigationService->save($model);
}
$order++;
}
} else {
// Create an array of current navigation handles to easy check via in_array
$currentNavHandles = array_column($currentNav, 'url');
// A menu item exists in our records, but not in the menu - delete
foreach ($generatedNav as $key => $value) {
if (!\in_array($value['handle'], $currentNavHandles, false)) {
$navModel = CpNav::$plugin->navigationService->getByHandle($layoutId, $value['handle']);
if ($navModel) {
CpNav::$plugin->navigationService->delete($navModel);
}
}
}
}
} | [
"public",
"function",
"regenerateNav",
"(",
"$",
"layoutId",
",",
"$",
"generatedNav",
",",
"$",
"currentNav",
")",
"{",
"// Find the extra or missing menu item",
"if",
"(",
"count",
"(",
"$",
"generatedNav",
")",
"<",
"count",
"(",
"$",
"currentNav",
")",
")",
"{",
"$",
"order",
"=",
"0",
";",
"// A menu item exists in the menu, but not in our records - add",
"foreach",
"(",
"$",
"currentNav",
"as",
"$",
"value",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"value",
"[",
"'url'",
"]",
")",
")",
"{",
"$",
"handle",
"=",
"str_replace",
"(",
"UrlHelper",
"::",
"url",
"(",
")",
".",
"'/'",
",",
"''",
",",
"$",
"value",
"[",
"'url'",
"]",
")",
";",
"}",
"else",
"{",
"$",
"handle",
"=",
"StringHelper",
"::",
"toKebabCase",
"(",
"$",
"value",
"[",
"'label'",
"]",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"generatedNav",
"[",
"$",
"handle",
"]",
")",
"&&",
"!",
"CpNav",
"::",
"$",
"plugin",
"->",
"navigationService",
"->",
"getByHandle",
"(",
"$",
"layoutId",
",",
"$",
"handle",
")",
")",
"{",
"$",
"icon",
"=",
"null",
";",
"// Check for custom icon (plugins)",
"if",
"(",
"isset",
"(",
"$",
"value",
"[",
"'icon'",
"]",
")",
")",
"{",
"$",
"icon",
"=",
"$",
"value",
"[",
"'icon'",
"]",
";",
"}",
"// Check for built-in Craft icon",
"if",
"(",
"isset",
"(",
"$",
"value",
"[",
"'fontIcon'",
"]",
")",
")",
"{",
"$",
"icon",
"=",
"$",
"value",
"[",
"'fontIcon'",
"]",
";",
"}",
"$",
"model",
"=",
"$",
"this",
"->",
"_prepareNavModel",
"(",
"[",
"'layoutId'",
"=>",
"$",
"layoutId",
",",
"'handle'",
"=>",
"$",
"handle",
",",
"'label'",
"=>",
"$",
"value",
"[",
"'label'",
"]",
",",
"'order'",
"=>",
"$",
"order",
",",
"'icon'",
"=>",
"$",
"icon",
",",
"'url'",
"=>",
"$",
"handle",
",",
"]",
")",
";",
"CpNav",
"::",
"$",
"plugin",
"->",
"navigationService",
"->",
"save",
"(",
"$",
"model",
")",
";",
"}",
"$",
"order",
"++",
";",
"}",
"}",
"else",
"{",
"// Create an array of current navigation handles to easy check via in_array",
"$",
"currentNavHandles",
"=",
"array_column",
"(",
"$",
"currentNav",
",",
"'url'",
")",
";",
"// A menu item exists in our records, but not in the menu - delete",
"foreach",
"(",
"$",
"generatedNav",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"\\",
"in_array",
"(",
"$",
"value",
"[",
"'handle'",
"]",
",",
"$",
"currentNavHandles",
",",
"false",
")",
")",
"{",
"$",
"navModel",
"=",
"CpNav",
"::",
"$",
"plugin",
"->",
"navigationService",
"->",
"getByHandle",
"(",
"$",
"layoutId",
",",
"$",
"value",
"[",
"'handle'",
"]",
")",
";",
"if",
"(",
"$",
"navModel",
")",
"{",
"CpNav",
"::",
"$",
"plugin",
"->",
"navigationService",
"->",
"delete",
"(",
"$",
"navModel",
")",
";",
"}",
"}",
"}",
"}",
"}"
]
| Creates or deletes records when the menu is updated by plugins
@param integer $layoutId
@param array $generatedNav
@param array $currentNav | [
"Creates",
"or",
"deletes",
"records",
"when",
"the",
"menu",
"is",
"updated",
"by",
"plugins"
]
| 04d258fa8a92fddb895a44b5c49cad9eabf256a3 | https://github.com/verbb/cp-nav/blob/04d258fa8a92fddb895a44b5c49cad9eabf256a3/src/services/CpNavService.php#L160-L217 | train |
vladkens/autoprefixer-php | lib/Autoprefixer.php | Autoprefixer.update | public function update()
{
$update_url = 'https://raw.github.com/ai/autoprefixer-rails/master/vendor/autoprefixer.js';
$local_path = __DIR__ . '/vendor/autoprefixer.js';
$new = file_get_contents($update_url);
$old = file_get_contents($local_path);
if (md5($new) == md5($old)) return false;
file_put_contents($local_path, $new);
return true;
} | php | public function update()
{
$update_url = 'https://raw.github.com/ai/autoprefixer-rails/master/vendor/autoprefixer.js';
$local_path = __DIR__ . '/vendor/autoprefixer.js';
$new = file_get_contents($update_url);
$old = file_get_contents($local_path);
if (md5($new) == md5($old)) return false;
file_put_contents($local_path, $new);
return true;
} | [
"public",
"function",
"update",
"(",
")",
"{",
"$",
"update_url",
"=",
"'https://raw.github.com/ai/autoprefixer-rails/master/vendor/autoprefixer.js'",
";",
"$",
"local_path",
"=",
"__DIR__",
".",
"'/vendor/autoprefixer.js'",
";",
"$",
"new",
"=",
"file_get_contents",
"(",
"$",
"update_url",
")",
";",
"$",
"old",
"=",
"file_get_contents",
"(",
"$",
"local_path",
")",
";",
"if",
"(",
"md5",
"(",
"$",
"new",
")",
"==",
"md5",
"(",
"$",
"old",
")",
")",
"return",
"false",
";",
"file_put_contents",
"(",
"$",
"local_path",
",",
"$",
"new",
")",
";",
"return",
"true",
";",
"}"
]
| Download autoprefixer updates.
@return bool True if updated. | [
"Download",
"autoprefixer",
"updates",
"."
]
| 72564d737c43bdaf206d5f2a83d30ddd042ec6b0 | https://github.com/vladkens/autoprefixer-php/blob/72564d737c43bdaf206d5f2a83d30ddd042ec6b0/lib/Autoprefixer.php#L91-L102 | train |
UseMuffin/Slug | src/Model/Behavior/SlugBehavior.php | SlugBehavior.buildValidator | public function buildValidator(Event $event, Validator $validator, $name)
{
foreach ((array)$this->getConfig('displayField') as $field) {
if (strpos($field, '.') === false) {
$validator->requirePresence($field, 'create')
->notEmpty($field);
}
}
} | php | public function buildValidator(Event $event, Validator $validator, $name)
{
foreach ((array)$this->getConfig('displayField') as $field) {
if (strpos($field, '.') === false) {
$validator->requirePresence($field, 'create')
->notEmpty($field);
}
}
} | [
"public",
"function",
"buildValidator",
"(",
"Event",
"$",
"event",
",",
"Validator",
"$",
"validator",
",",
"$",
"name",
")",
"{",
"foreach",
"(",
"(",
"array",
")",
"$",
"this",
"->",
"getConfig",
"(",
"'displayField'",
")",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"field",
",",
"'.'",
")",
"===",
"false",
")",
"{",
"$",
"validator",
"->",
"requirePresence",
"(",
"$",
"field",
",",
"'create'",
")",
"->",
"notEmpty",
"(",
"$",
"field",
")",
";",
"}",
"}",
"}"
]
| Callback for Model.buildValidator event.
@param \Cake\Event\Event $event The beforeSave event that was fired.
@param \Cake\Validation\Validator $validator Validator instance.
@param string $name Validator name.
@return void | [
"Callback",
"for",
"Model",
".",
"buildValidator",
"event",
"."
]
| e36fe293fe4fe65db9e10528dfd54beb0edfa226 | https://github.com/UseMuffin/Slug/blob/e36fe293fe4fe65db9e10528dfd54beb0edfa226/src/Model/Behavior/SlugBehavior.php#L180-L188 | train |
UseMuffin/Slug | src/Model/Behavior/SlugBehavior.php | SlugBehavior.beforeSave | public function beforeSave(Event $event, Entity $entity, ArrayObject $options)
{
$onUpdate = $this->getConfig('onUpdate');
if (!$entity->isNew() && !$onUpdate) {
return;
}
$onDirty = $this->getConfig('onDirty');
$field = $this->getConfig('field');
if (!$onDirty
&& $entity->isDirty($field)
&& (!$entity->isNew() || (!empty($entity->{$field})))
) {
return;
}
$separator = $this->getConfig('separator');
if ($entity->isDirty($field) && !empty($entity->{$field})) {
$slug = $this->slug($entity, $entity->{$field}, $separator);
$entity->set($field, $slug);
return;
}
$parts = $this->_getPartsFromEntity($entity);
if (empty($parts)) {
return;
}
$slug = $this->slug($entity, implode($separator, $parts), $separator);
$entity->set($field, $slug);
} | php | public function beforeSave(Event $event, Entity $entity, ArrayObject $options)
{
$onUpdate = $this->getConfig('onUpdate');
if (!$entity->isNew() && !$onUpdate) {
return;
}
$onDirty = $this->getConfig('onDirty');
$field = $this->getConfig('field');
if (!$onDirty
&& $entity->isDirty($field)
&& (!$entity->isNew() || (!empty($entity->{$field})))
) {
return;
}
$separator = $this->getConfig('separator');
if ($entity->isDirty($field) && !empty($entity->{$field})) {
$slug = $this->slug($entity, $entity->{$field}, $separator);
$entity->set($field, $slug);
return;
}
$parts = $this->_getPartsFromEntity($entity);
if (empty($parts)) {
return;
}
$slug = $this->slug($entity, implode($separator, $parts), $separator);
$entity->set($field, $slug);
} | [
"public",
"function",
"beforeSave",
"(",
"Event",
"$",
"event",
",",
"Entity",
"$",
"entity",
",",
"ArrayObject",
"$",
"options",
")",
"{",
"$",
"onUpdate",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'onUpdate'",
")",
";",
"if",
"(",
"!",
"$",
"entity",
"->",
"isNew",
"(",
")",
"&&",
"!",
"$",
"onUpdate",
")",
"{",
"return",
";",
"}",
"$",
"onDirty",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'onDirty'",
")",
";",
"$",
"field",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'field'",
")",
";",
"if",
"(",
"!",
"$",
"onDirty",
"&&",
"$",
"entity",
"->",
"isDirty",
"(",
"$",
"field",
")",
"&&",
"(",
"!",
"$",
"entity",
"->",
"isNew",
"(",
")",
"||",
"(",
"!",
"empty",
"(",
"$",
"entity",
"->",
"{",
"$",
"field",
"}",
")",
")",
")",
")",
"{",
"return",
";",
"}",
"$",
"separator",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'separator'",
")",
";",
"if",
"(",
"$",
"entity",
"->",
"isDirty",
"(",
"$",
"field",
")",
"&&",
"!",
"empty",
"(",
"$",
"entity",
"->",
"{",
"$",
"field",
"}",
")",
")",
"{",
"$",
"slug",
"=",
"$",
"this",
"->",
"slug",
"(",
"$",
"entity",
",",
"$",
"entity",
"->",
"{",
"$",
"field",
"}",
",",
"$",
"separator",
")",
";",
"$",
"entity",
"->",
"set",
"(",
"$",
"field",
",",
"$",
"slug",
")",
";",
"return",
";",
"}",
"$",
"parts",
"=",
"$",
"this",
"->",
"_getPartsFromEntity",
"(",
"$",
"entity",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"parts",
")",
")",
"{",
"return",
";",
"}",
"$",
"slug",
"=",
"$",
"this",
"->",
"slug",
"(",
"$",
"entity",
",",
"implode",
"(",
"$",
"separator",
",",
"$",
"parts",
")",
",",
"$",
"separator",
")",
";",
"$",
"entity",
"->",
"set",
"(",
"$",
"field",
",",
"$",
"slug",
")",
";",
"}"
]
| Callback for Model.beforeSave event.
@param \Cake\Event\Event $event The afterSave event that was fired.
@param \Cake\ORM\Entity $entity The entity that was saved.
@param \ArrayObject $options Options.
@return void | [
"Callback",
"for",
"Model",
".",
"beforeSave",
"event",
"."
]
| e36fe293fe4fe65db9e10528dfd54beb0edfa226 | https://github.com/UseMuffin/Slug/blob/e36fe293fe4fe65db9e10528dfd54beb0edfa226/src/Model/Behavior/SlugBehavior.php#L198-L229 | train |
UseMuffin/Slug | src/Model/Behavior/SlugBehavior.php | SlugBehavior._getPartsFromEntity | protected function _getPartsFromEntity($entity)
{
$parts = [];
foreach ((array)$this->getConfig('displayField') as $displayField) {
$value = Hash::get($entity, $displayField);
if ($value === null && !$entity->isNew()) {
return [];
}
if (!empty($value) || is_numeric($value)) {
$parts[] = $value;
}
}
return $parts;
} | php | protected function _getPartsFromEntity($entity)
{
$parts = [];
foreach ((array)$this->getConfig('displayField') as $displayField) {
$value = Hash::get($entity, $displayField);
if ($value === null && !$entity->isNew()) {
return [];
}
if (!empty($value) || is_numeric($value)) {
$parts[] = $value;
}
}
return $parts;
} | [
"protected",
"function",
"_getPartsFromEntity",
"(",
"$",
"entity",
")",
"{",
"$",
"parts",
"=",
"[",
"]",
";",
"foreach",
"(",
"(",
"array",
")",
"$",
"this",
"->",
"getConfig",
"(",
"'displayField'",
")",
"as",
"$",
"displayField",
")",
"{",
"$",
"value",
"=",
"Hash",
"::",
"get",
"(",
"$",
"entity",
",",
"$",
"displayField",
")",
";",
"if",
"(",
"$",
"value",
"===",
"null",
"&&",
"!",
"$",
"entity",
"->",
"isNew",
"(",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
"||",
"is_numeric",
"(",
"$",
"value",
")",
")",
"{",
"$",
"parts",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"return",
"$",
"parts",
";",
"}"
]
| Gets the parts from an entity
@param \Cake\Datasource\EntityInterface $entity Entity
@return array | [
"Gets",
"the",
"parts",
"from",
"an",
"entity"
]
| e36fe293fe4fe65db9e10528dfd54beb0edfa226 | https://github.com/UseMuffin/Slug/blob/e36fe293fe4fe65db9e10528dfd54beb0edfa226/src/Model/Behavior/SlugBehavior.php#L237-L253 | train |
UseMuffin/Slug | src/Model/Behavior/SlugBehavior.php | SlugBehavior.findSlugged | public function findSlugged(Query $query, array $options)
{
if (!isset($options['slug'])) {
throw new InvalidArgumentException('The `slug` key is required by the `slugged` finder.');
}
return $query->where([
$this->_table->aliasField($this->getConfig('field')) => $options['slug'],
]);
} | php | public function findSlugged(Query $query, array $options)
{
if (!isset($options['slug'])) {
throw new InvalidArgumentException('The `slug` key is required by the `slugged` finder.');
}
return $query->where([
$this->_table->aliasField($this->getConfig('field')) => $options['slug'],
]);
} | [
"public",
"function",
"findSlugged",
"(",
"Query",
"$",
"query",
",",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'slug'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'The `slug` key is required by the `slugged` finder.'",
")",
";",
"}",
"return",
"$",
"query",
"->",
"where",
"(",
"[",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'field'",
")",
")",
"=>",
"$",
"options",
"[",
"'slug'",
"]",
",",
"]",
")",
";",
"}"
]
| Custom finder.
@param \Cake\ORM\Query $query Query.
@param array $options Options.
@return \Cake\ORM\Query Query. | [
"Custom",
"finder",
"."
]
| e36fe293fe4fe65db9e10528dfd54beb0edfa226 | https://github.com/UseMuffin/Slug/blob/e36fe293fe4fe65db9e10528dfd54beb0edfa226/src/Model/Behavior/SlugBehavior.php#L262-L271 | train |
UseMuffin/Slug | src/Model/Behavior/SlugBehavior.php | SlugBehavior.slug | public function slug($entity, $string = null, $separator = null)
{
if ($separator === null) {
$separator = $this->getConfig('separator');
}
if (is_string($entity)) {
if ($string !== null) {
$separator = $string;
}
$string = $entity;
unset($entity);
} elseif (($entity instanceof Entity) && $string === null) {
$string = $this->_getSlugStringFromEntity($entity, $separator);
}
$slug = $this->_slug($string, $separator);
$unique = $this->getConfig('unique');
if (isset($entity) && $unique) {
$slug = $unique($entity, $slug, $separator);
}
return $slug;
} | php | public function slug($entity, $string = null, $separator = null)
{
if ($separator === null) {
$separator = $this->getConfig('separator');
}
if (is_string($entity)) {
if ($string !== null) {
$separator = $string;
}
$string = $entity;
unset($entity);
} elseif (($entity instanceof Entity) && $string === null) {
$string = $this->_getSlugStringFromEntity($entity, $separator);
}
$slug = $this->_slug($string, $separator);
$unique = $this->getConfig('unique');
if (isset($entity) && $unique) {
$slug = $unique($entity, $slug, $separator);
}
return $slug;
} | [
"public",
"function",
"slug",
"(",
"$",
"entity",
",",
"$",
"string",
"=",
"null",
",",
"$",
"separator",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"separator",
"===",
"null",
")",
"{",
"$",
"separator",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'separator'",
")",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"entity",
")",
")",
"{",
"if",
"(",
"$",
"string",
"!==",
"null",
")",
"{",
"$",
"separator",
"=",
"$",
"string",
";",
"}",
"$",
"string",
"=",
"$",
"entity",
";",
"unset",
"(",
"$",
"entity",
")",
";",
"}",
"elseif",
"(",
"(",
"$",
"entity",
"instanceof",
"Entity",
")",
"&&",
"$",
"string",
"===",
"null",
")",
"{",
"$",
"string",
"=",
"$",
"this",
"->",
"_getSlugStringFromEntity",
"(",
"$",
"entity",
",",
"$",
"separator",
")",
";",
"}",
"$",
"slug",
"=",
"$",
"this",
"->",
"_slug",
"(",
"$",
"string",
",",
"$",
"separator",
")",
";",
"$",
"unique",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'unique'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"entity",
")",
"&&",
"$",
"unique",
")",
"{",
"$",
"slug",
"=",
"$",
"unique",
"(",
"$",
"entity",
",",
"$",
"slug",
",",
"$",
"separator",
")",
";",
"}",
"return",
"$",
"slug",
";",
"}"
]
| Generates slug.
@param \Cake\ORM\Entity|string $entity Entity to create slug for
@param string $string String to create slug for.
@param string|null $separator Separator.
@return string Slug. | [
"Generates",
"slug",
"."
]
| e36fe293fe4fe65db9e10528dfd54beb0edfa226 | https://github.com/UseMuffin/Slug/blob/e36fe293fe4fe65db9e10528dfd54beb0edfa226/src/Model/Behavior/SlugBehavior.php#L281-L305 | train |
UseMuffin/Slug | src/Model/Behavior/SlugBehavior.php | SlugBehavior._getSlugStringFromEntity | protected function _getSlugStringFromEntity($entity, $separator)
{
$string = [];
foreach ((array)$this->getConfig('displayField') as $field) {
if ($entity->getError($field)) {
throw new InvalidArgumentException(sprintf('Error while generating the slug, the field `%s` contains an invalid value.', $field));
}
$string[] = $value = Hash::get($entity, $field);
}
return implode($separator, $string);
} | php | protected function _getSlugStringFromEntity($entity, $separator)
{
$string = [];
foreach ((array)$this->getConfig('displayField') as $field) {
if ($entity->getError($field)) {
throw new InvalidArgumentException(sprintf('Error while generating the slug, the field `%s` contains an invalid value.', $field));
}
$string[] = $value = Hash::get($entity, $field);
}
return implode($separator, $string);
} | [
"protected",
"function",
"_getSlugStringFromEntity",
"(",
"$",
"entity",
",",
"$",
"separator",
")",
"{",
"$",
"string",
"=",
"[",
"]",
";",
"foreach",
"(",
"(",
"array",
")",
"$",
"this",
"->",
"getConfig",
"(",
"'displayField'",
")",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"$",
"entity",
"->",
"getError",
"(",
"$",
"field",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Error while generating the slug, the field `%s` contains an invalid value.'",
",",
"$",
"field",
")",
")",
";",
"}",
"$",
"string",
"[",
"]",
"=",
"$",
"value",
"=",
"Hash",
"::",
"get",
"(",
"$",
"entity",
",",
"$",
"field",
")",
";",
"}",
"return",
"implode",
"(",
"$",
"separator",
",",
"$",
"string",
")",
";",
"}"
]
| Gets the slug string based on an entity
@param \Cake\Datasource\EntityInterface $entity Entity
@param string $separator Separator
@return string | [
"Gets",
"the",
"slug",
"string",
"based",
"on",
"an",
"entity"
]
| e36fe293fe4fe65db9e10528dfd54beb0edfa226 | https://github.com/UseMuffin/Slug/blob/e36fe293fe4fe65db9e10528dfd54beb0edfa226/src/Model/Behavior/SlugBehavior.php#L314-L325 | train |
UseMuffin/Slug | src/Model/Behavior/SlugBehavior.php | SlugBehavior._conditions | protected function _conditions($entity, $slug)
{
/** @var string $primaryKey */
$primaryKey = $this->_table->getPrimaryKey();
$field = $this->_table->aliasField($this->getConfig('field'));
$conditions = [$field => $slug];
if (is_callable($this->getConfig('scope'))) {
$scope = $this->getConfig('scope');
$conditions += $scope($entity);
} else {
$conditions += $this->getConfig('scope');
}
if ($id = $entity->{$primaryKey}) {
$conditions['NOT'][$this->_table->aliasField($primaryKey)] = $id;
}
return $conditions;
} | php | protected function _conditions($entity, $slug)
{
/** @var string $primaryKey */
$primaryKey = $this->_table->getPrimaryKey();
$field = $this->_table->aliasField($this->getConfig('field'));
$conditions = [$field => $slug];
if (is_callable($this->getConfig('scope'))) {
$scope = $this->getConfig('scope');
$conditions += $scope($entity);
} else {
$conditions += $this->getConfig('scope');
}
if ($id = $entity->{$primaryKey}) {
$conditions['NOT'][$this->_table->aliasField($primaryKey)] = $id;
}
return $conditions;
} | [
"protected",
"function",
"_conditions",
"(",
"$",
"entity",
",",
"$",
"slug",
")",
"{",
"/** @var string $primaryKey */",
"$",
"primaryKey",
"=",
"$",
"this",
"->",
"_table",
"->",
"getPrimaryKey",
"(",
")",
";",
"$",
"field",
"=",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'field'",
")",
")",
";",
"$",
"conditions",
"=",
"[",
"$",
"field",
"=>",
"$",
"slug",
"]",
";",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'scope'",
")",
")",
")",
"{",
"$",
"scope",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'scope'",
")",
";",
"$",
"conditions",
"+=",
"$",
"scope",
"(",
"$",
"entity",
")",
";",
"}",
"else",
"{",
"$",
"conditions",
"+=",
"$",
"this",
"->",
"getConfig",
"(",
"'scope'",
")",
";",
"}",
"if",
"(",
"$",
"id",
"=",
"$",
"entity",
"->",
"{",
"$",
"primaryKey",
"}",
")",
"{",
"$",
"conditions",
"[",
"'NOT'",
"]",
"[",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"primaryKey",
")",
"]",
"=",
"$",
"id",
";",
"}",
"return",
"$",
"conditions",
";",
"}"
]
| Builds the conditions
@param \Cake\ORM\Entity $entity Entity.
@param string $slug Slug
@return array | [
"Builds",
"the",
"conditions"
]
| e36fe293fe4fe65db9e10528dfd54beb0edfa226 | https://github.com/UseMuffin/Slug/blob/e36fe293fe4fe65db9e10528dfd54beb0edfa226/src/Model/Behavior/SlugBehavior.php#L334-L354 | train |
UseMuffin/Slug | src/Model/Behavior/SlugBehavior.php | SlugBehavior._uniqueSlug | protected function _uniqueSlug(Entity $entity, $slug, $separator)
{
/** @var string $primaryKey */
$primaryKey = $this->_table->getPrimaryKey();
$field = $this->_table->aliasField($this->getConfig('field'));
$conditions = $this->_conditions($entity, $slug);
$i = 0;
$suffix = '';
$length = $this->getConfig('maxLength');
while ($this->_table->exists($conditions)) {
$i++;
$suffix = $separator . $i;
if ($length && $length < mb_strlen($slug . $suffix)) {
$slug = mb_substr($slug, 0, $length - mb_strlen($suffix));
}
$conditions[$field] = $slug . $suffix;
}
return $slug . $suffix;
} | php | protected function _uniqueSlug(Entity $entity, $slug, $separator)
{
/** @var string $primaryKey */
$primaryKey = $this->_table->getPrimaryKey();
$field = $this->_table->aliasField($this->getConfig('field'));
$conditions = $this->_conditions($entity, $slug);
$i = 0;
$suffix = '';
$length = $this->getConfig('maxLength');
while ($this->_table->exists($conditions)) {
$i++;
$suffix = $separator . $i;
if ($length && $length < mb_strlen($slug . $suffix)) {
$slug = mb_substr($slug, 0, $length - mb_strlen($suffix));
}
$conditions[$field] = $slug . $suffix;
}
return $slug . $suffix;
} | [
"protected",
"function",
"_uniqueSlug",
"(",
"Entity",
"$",
"entity",
",",
"$",
"slug",
",",
"$",
"separator",
")",
"{",
"/** @var string $primaryKey */",
"$",
"primaryKey",
"=",
"$",
"this",
"->",
"_table",
"->",
"getPrimaryKey",
"(",
")",
";",
"$",
"field",
"=",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'field'",
")",
")",
";",
"$",
"conditions",
"=",
"$",
"this",
"->",
"_conditions",
"(",
"$",
"entity",
",",
"$",
"slug",
")",
";",
"$",
"i",
"=",
"0",
";",
"$",
"suffix",
"=",
"''",
";",
"$",
"length",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'maxLength'",
")",
";",
"while",
"(",
"$",
"this",
"->",
"_table",
"->",
"exists",
"(",
"$",
"conditions",
")",
")",
"{",
"$",
"i",
"++",
";",
"$",
"suffix",
"=",
"$",
"separator",
".",
"$",
"i",
";",
"if",
"(",
"$",
"length",
"&&",
"$",
"length",
"<",
"mb_strlen",
"(",
"$",
"slug",
".",
"$",
"suffix",
")",
")",
"{",
"$",
"slug",
"=",
"mb_substr",
"(",
"$",
"slug",
",",
"0",
",",
"$",
"length",
"-",
"mb_strlen",
"(",
"$",
"suffix",
")",
")",
";",
"}",
"$",
"conditions",
"[",
"$",
"field",
"]",
"=",
"$",
"slug",
".",
"$",
"suffix",
";",
"}",
"return",
"$",
"slug",
".",
"$",
"suffix",
";",
"}"
]
| Returns a unique slug.
@param \Cake\ORM\Entity $entity Entity.
@param string $slug Slug.
@param string $separator Separator.
@return string Unique slug. | [
"Returns",
"a",
"unique",
"slug",
"."
]
| e36fe293fe4fe65db9e10528dfd54beb0edfa226 | https://github.com/UseMuffin/Slug/blob/e36fe293fe4fe65db9e10528dfd54beb0edfa226/src/Model/Behavior/SlugBehavior.php#L364-L386 | train |
UseMuffin/Slug | src/Model/Behavior/SlugBehavior.php | SlugBehavior._slug | protected function _slug($string, $separator)
{
$replacements = $this->getConfig('replacements');
$callable = $this->slugger();
if (is_object($callable) && $callable instanceof SluggerInterface) {
$callable = [$callable, 'slug'];
}
$slug = $callable(str_replace(array_keys($replacements), $replacements, $string), $separator);
if (!empty($this->getConfig('maxLength'))) {
$slug = Text::truncate(
$slug,
$this->getConfig('maxLength'),
['ellipsis' => '']
);
}
return $slug;
} | php | protected function _slug($string, $separator)
{
$replacements = $this->getConfig('replacements');
$callable = $this->slugger();
if (is_object($callable) && $callable instanceof SluggerInterface) {
$callable = [$callable, 'slug'];
}
$slug = $callable(str_replace(array_keys($replacements), $replacements, $string), $separator);
if (!empty($this->getConfig('maxLength'))) {
$slug = Text::truncate(
$slug,
$this->getConfig('maxLength'),
['ellipsis' => '']
);
}
return $slug;
} | [
"protected",
"function",
"_slug",
"(",
"$",
"string",
",",
"$",
"separator",
")",
"{",
"$",
"replacements",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'replacements'",
")",
";",
"$",
"callable",
"=",
"$",
"this",
"->",
"slugger",
"(",
")",
";",
"if",
"(",
"is_object",
"(",
"$",
"callable",
")",
"&&",
"$",
"callable",
"instanceof",
"SluggerInterface",
")",
"{",
"$",
"callable",
"=",
"[",
"$",
"callable",
",",
"'slug'",
"]",
";",
"}",
"$",
"slug",
"=",
"$",
"callable",
"(",
"str_replace",
"(",
"array_keys",
"(",
"$",
"replacements",
")",
",",
"$",
"replacements",
",",
"$",
"string",
")",
",",
"$",
"separator",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'maxLength'",
")",
")",
")",
"{",
"$",
"slug",
"=",
"Text",
"::",
"truncate",
"(",
"$",
"slug",
",",
"$",
"this",
"->",
"getConfig",
"(",
"'maxLength'",
")",
",",
"[",
"'ellipsis'",
"=>",
"''",
"]",
")",
";",
"}",
"return",
"$",
"slug",
";",
"}"
]
| Proxies the defined slugger's `slug` method.
@param string $string String to create a slug from.
@param string $separator String to use as separator/separator.
@return string Slug. | [
"Proxies",
"the",
"defined",
"slugger",
"s",
"slug",
"method",
"."
]
| e36fe293fe4fe65db9e10528dfd54beb0edfa226 | https://github.com/UseMuffin/Slug/blob/e36fe293fe4fe65db9e10528dfd54beb0edfa226/src/Model/Behavior/SlugBehavior.php#L395-L412 | train |
timoh6/GenPhrase | library/GenPhrase/Password.php | Password.generate | public function generate($bits = 50.0)
{
$bits = (float) $bits;
$separators = $this->getSeparators();
$separatorBits = $this->precisionFloat(log(strlen($separators), 2));
$passPhrase = '';
try
{
if ($bits < self::MIN_ENTROPY_BITS || $bits > self::MAX_ENTROPY_BITS)
{
throw new \InvalidArgumentException('Invalid parameter: $bits must be between ' . self::MIN_ENTROPY_BITS . ' and ' . self::MAX_ENTROPY_BITS);
}
$words = $this->_wordlistHandler->getWordsAsArray();
$count = count($words);
if ($count < self::MIN_WORD_COUNT)
{
throw new \RuntimeException('Wordlist must have at least ' . self::MIN_WORD_COUNT . ' unique words');
}
$countForBits = $count;
if ($this->_disableWordModifier !== true)
{
$countForBits = $countForBits * $this->_wordModifier->getWordCountMultiplier();
}
$wordBits = $this->precisionFloat(log($countForBits, 2));
if ($wordBits < 1)
{
throw new \RuntimeException('Words does not have enough bits to create a passphrase');
}
$maxIndex = $count;
if ($this->_disableSeparators === true)
{
$useSeparators = false;
}
else if ($this->_alwaysUseSeparators)
{
$useSeparators = true;
}
else
{
$useSeparators = $this->makesSenseToUseSeparators($bits, $wordBits, $separatorBits);
}
do
{
$index = $this->_randomProvider->getElement($maxIndex);
$word = $words[$index];
if ($this->_disableWordModifier !== true)
{
$word = $this->_wordModifier->modify($word, $this->_encoding);
}
$passPhrase .= $word;
$bits -= $wordBits;
if ($bits > $separatorBits && $useSeparators === true && isset($separators[0]))
{
// At least two separator characters
if (isset($separators[1]))
{
$passPhrase .= $separators[$this->_randomProvider->getElement(strlen($separators))];
$bits -= $separatorBits;
}
else
{
$passPhrase .= $separators[0];
}
}
else if ($bits > 0.0)
{
$passPhrase .= ' ';
}
}
while ($bits > 0.0);
}
catch (\Exception $e)
{
throw $e;
}
return $passPhrase;
} | php | public function generate($bits = 50.0)
{
$bits = (float) $bits;
$separators = $this->getSeparators();
$separatorBits = $this->precisionFloat(log(strlen($separators), 2));
$passPhrase = '';
try
{
if ($bits < self::MIN_ENTROPY_BITS || $bits > self::MAX_ENTROPY_BITS)
{
throw new \InvalidArgumentException('Invalid parameter: $bits must be between ' . self::MIN_ENTROPY_BITS . ' and ' . self::MAX_ENTROPY_BITS);
}
$words = $this->_wordlistHandler->getWordsAsArray();
$count = count($words);
if ($count < self::MIN_WORD_COUNT)
{
throw new \RuntimeException('Wordlist must have at least ' . self::MIN_WORD_COUNT . ' unique words');
}
$countForBits = $count;
if ($this->_disableWordModifier !== true)
{
$countForBits = $countForBits * $this->_wordModifier->getWordCountMultiplier();
}
$wordBits = $this->precisionFloat(log($countForBits, 2));
if ($wordBits < 1)
{
throw new \RuntimeException('Words does not have enough bits to create a passphrase');
}
$maxIndex = $count;
if ($this->_disableSeparators === true)
{
$useSeparators = false;
}
else if ($this->_alwaysUseSeparators)
{
$useSeparators = true;
}
else
{
$useSeparators = $this->makesSenseToUseSeparators($bits, $wordBits, $separatorBits);
}
do
{
$index = $this->_randomProvider->getElement($maxIndex);
$word = $words[$index];
if ($this->_disableWordModifier !== true)
{
$word = $this->_wordModifier->modify($word, $this->_encoding);
}
$passPhrase .= $word;
$bits -= $wordBits;
if ($bits > $separatorBits && $useSeparators === true && isset($separators[0]))
{
// At least two separator characters
if (isset($separators[1]))
{
$passPhrase .= $separators[$this->_randomProvider->getElement(strlen($separators))];
$bits -= $separatorBits;
}
else
{
$passPhrase .= $separators[0];
}
}
else if ($bits > 0.0)
{
$passPhrase .= ' ';
}
}
while ($bits > 0.0);
}
catch (\Exception $e)
{
throw $e;
}
return $passPhrase;
} | [
"public",
"function",
"generate",
"(",
"$",
"bits",
"=",
"50.0",
")",
"{",
"$",
"bits",
"=",
"(",
"float",
")",
"$",
"bits",
";",
"$",
"separators",
"=",
"$",
"this",
"->",
"getSeparators",
"(",
")",
";",
"$",
"separatorBits",
"=",
"$",
"this",
"->",
"precisionFloat",
"(",
"log",
"(",
"strlen",
"(",
"$",
"separators",
")",
",",
"2",
")",
")",
";",
"$",
"passPhrase",
"=",
"''",
";",
"try",
"{",
"if",
"(",
"$",
"bits",
"<",
"self",
"::",
"MIN_ENTROPY_BITS",
"||",
"$",
"bits",
">",
"self",
"::",
"MAX_ENTROPY_BITS",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Invalid parameter: $bits must be between '",
".",
"self",
"::",
"MIN_ENTROPY_BITS",
".",
"' and '",
".",
"self",
"::",
"MAX_ENTROPY_BITS",
")",
";",
"}",
"$",
"words",
"=",
"$",
"this",
"->",
"_wordlistHandler",
"->",
"getWordsAsArray",
"(",
")",
";",
"$",
"count",
"=",
"count",
"(",
"$",
"words",
")",
";",
"if",
"(",
"$",
"count",
"<",
"self",
"::",
"MIN_WORD_COUNT",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Wordlist must have at least '",
".",
"self",
"::",
"MIN_WORD_COUNT",
".",
"' unique words'",
")",
";",
"}",
"$",
"countForBits",
"=",
"$",
"count",
";",
"if",
"(",
"$",
"this",
"->",
"_disableWordModifier",
"!==",
"true",
")",
"{",
"$",
"countForBits",
"=",
"$",
"countForBits",
"*",
"$",
"this",
"->",
"_wordModifier",
"->",
"getWordCountMultiplier",
"(",
")",
";",
"}",
"$",
"wordBits",
"=",
"$",
"this",
"->",
"precisionFloat",
"(",
"log",
"(",
"$",
"countForBits",
",",
"2",
")",
")",
";",
"if",
"(",
"$",
"wordBits",
"<",
"1",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Words does not have enough bits to create a passphrase'",
")",
";",
"}",
"$",
"maxIndex",
"=",
"$",
"count",
";",
"if",
"(",
"$",
"this",
"->",
"_disableSeparators",
"===",
"true",
")",
"{",
"$",
"useSeparators",
"=",
"false",
";",
"}",
"else",
"if",
"(",
"$",
"this",
"->",
"_alwaysUseSeparators",
")",
"{",
"$",
"useSeparators",
"=",
"true",
";",
"}",
"else",
"{",
"$",
"useSeparators",
"=",
"$",
"this",
"->",
"makesSenseToUseSeparators",
"(",
"$",
"bits",
",",
"$",
"wordBits",
",",
"$",
"separatorBits",
")",
";",
"}",
"do",
"{",
"$",
"index",
"=",
"$",
"this",
"->",
"_randomProvider",
"->",
"getElement",
"(",
"$",
"maxIndex",
")",
";",
"$",
"word",
"=",
"$",
"words",
"[",
"$",
"index",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"_disableWordModifier",
"!==",
"true",
")",
"{",
"$",
"word",
"=",
"$",
"this",
"->",
"_wordModifier",
"->",
"modify",
"(",
"$",
"word",
",",
"$",
"this",
"->",
"_encoding",
")",
";",
"}",
"$",
"passPhrase",
".=",
"$",
"word",
";",
"$",
"bits",
"-=",
"$",
"wordBits",
";",
"if",
"(",
"$",
"bits",
">",
"$",
"separatorBits",
"&&",
"$",
"useSeparators",
"===",
"true",
"&&",
"isset",
"(",
"$",
"separators",
"[",
"0",
"]",
")",
")",
"{",
"// At least two separator characters",
"if",
"(",
"isset",
"(",
"$",
"separators",
"[",
"1",
"]",
")",
")",
"{",
"$",
"passPhrase",
".=",
"$",
"separators",
"[",
"$",
"this",
"->",
"_randomProvider",
"->",
"getElement",
"(",
"strlen",
"(",
"$",
"separators",
")",
")",
"]",
";",
"$",
"bits",
"-=",
"$",
"separatorBits",
";",
"}",
"else",
"{",
"$",
"passPhrase",
".=",
"$",
"separators",
"[",
"0",
"]",
";",
"}",
"}",
"else",
"if",
"(",
"$",
"bits",
">",
"0.0",
")",
"{",
"$",
"passPhrase",
".=",
"' '",
";",
"}",
"}",
"while",
"(",
"$",
"bits",
">",
"0.0",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"$",
"e",
";",
"}",
"return",
"$",
"passPhrase",
";",
"}"
]
| Generates a passphrase based on supplied wordlists, separators, entropy
bits and word modifier.
@param float $bits
@return string
@throws \InvalidArgumentException
@throws \RuntimeException
@throws \RangeException | [
"Generates",
"a",
"passphrase",
"based",
"on",
"supplied",
"wordlists",
"separators",
"entropy",
"bits",
"and",
"word",
"modifier",
"."
]
| 4b7e2b3ba6ce369b3a10e9c31e4e9dc63effe564 | https://github.com/timoh6/GenPhrase/blob/4b7e2b3ba6ce369b3a10e9c31e4e9dc63effe564/library/GenPhrase/Password.php#L107-L194 | train |
timoh6/GenPhrase | library/GenPhrase/Password.php | Password.makesSenseToUseSeparators | public function makesSenseToUseSeparators($bits, $wordBits, $separatorBits)
{
$wordCount = 1 + ($bits + (($wordBits + $separatorBits - 1) - $wordBits)) / ($wordBits + $separatorBits);
return ((int) (($bits + ($wordBits - 1)) / $wordBits) !== (int) $wordCount);
} | php | public function makesSenseToUseSeparators($bits, $wordBits, $separatorBits)
{
$wordCount = 1 + ($bits + (($wordBits + $separatorBits - 1) - $wordBits)) / ($wordBits + $separatorBits);
return ((int) (($bits + ($wordBits - 1)) / $wordBits) !== (int) $wordCount);
} | [
"public",
"function",
"makesSenseToUseSeparators",
"(",
"$",
"bits",
",",
"$",
"wordBits",
",",
"$",
"separatorBits",
")",
"{",
"$",
"wordCount",
"=",
"1",
"+",
"(",
"$",
"bits",
"+",
"(",
"(",
"$",
"wordBits",
"+",
"$",
"separatorBits",
"-",
"1",
")",
"-",
"$",
"wordBits",
")",
")",
"/",
"(",
"$",
"wordBits",
"+",
"$",
"separatorBits",
")",
";",
"return",
"(",
"(",
"int",
")",
"(",
"(",
"$",
"bits",
"+",
"(",
"$",
"wordBits",
"-",
"1",
")",
")",
"/",
"$",
"wordBits",
")",
"!==",
"(",
"int",
")",
"$",
"wordCount",
")",
";",
"}"
]
| Detects whether it is sensible to use separator characters.
@param float $bits
@param float $wordBits
@param float $separatorBits
@return boolean | [
"Detects",
"whether",
"it",
"is",
"sensible",
"to",
"use",
"separator",
"characters",
"."
]
| 4b7e2b3ba6ce369b3a10e9c31e4e9dc63effe564 | https://github.com/timoh6/GenPhrase/blob/4b7e2b3ba6ce369b3a10e9c31e4e9dc63effe564/library/GenPhrase/Password.php#L313-L318 | train |
timoh6/GenPhrase | library/GenPhrase/Random/RandomBytes.php | RandomBytes.getRandomBytes | public function getRandomBytes($count)
{
$count = (int) $count;
$bytes = '';
$hasBytes = false;
if (version_compare(PHP_VERSION, '7.0.0') >= 0 && function_exists('random_bytes'))
{
try
{
$bytes = \random_bytes($count);
$hasBytes = true;
}
catch (\Exception $e)
{
//
}
}
// Make sure PHP version is at least 5.3. We do this because
// mcrypt_create_iv() on older versions of PHP
// does not give "strong" random data on Windows systems.
if (version_compare(PHP_VERSION, '5.3.0') >= 0 && function_exists('mcrypt_create_iv'))
{
// Suppress deprecation warning in PHP 7.1
$tmp = @mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
if ($tmp !== false)
{
$bytes = $tmp;
$hasBytes = true;
}
}
if ($hasBytes === false && file_exists('/dev/urandom') && is_readable('/dev/urandom') && (false !== ($fh = fopen('/dev/urandom', 'rb'))))
{
if (function_exists('stream_set_read_buffer'))
{
stream_set_read_buffer($fh, 0);
}
$tmp = fread($fh, $count);
fclose($fh);
if ($tmp !== false)
{
$bytes = $tmp;
$hasBytes = true;
}
}
/*
* We want to play it safe and disable openssl_random_pseudo_bytes() for now.
* This is due to the OpenSSL "PID wrapping bug", which potentially could affect GenPhrase.
*
if ($hasBytes === false && version_compare(PHP_VERSION, '5.3.4') >= 0 && function_exists('openssl_random_pseudo_bytes'))
{
$tmp = openssl_random_pseudo_bytes($count, $cryptoStrong);
if ($tmp !== false && $cryptoStrong === true)
{
$bytes = $tmp;
$hasBytes = true;
}
}
*/
if (isset($bytes[$count - 1]) && !isset($bytes[$count]))
{
return $bytes;
}
else
{
return false;
}
} | php | public function getRandomBytes($count)
{
$count = (int) $count;
$bytes = '';
$hasBytes = false;
if (version_compare(PHP_VERSION, '7.0.0') >= 0 && function_exists('random_bytes'))
{
try
{
$bytes = \random_bytes($count);
$hasBytes = true;
}
catch (\Exception $e)
{
//
}
}
// Make sure PHP version is at least 5.3. We do this because
// mcrypt_create_iv() on older versions of PHP
// does not give "strong" random data on Windows systems.
if (version_compare(PHP_VERSION, '5.3.0') >= 0 && function_exists('mcrypt_create_iv'))
{
// Suppress deprecation warning in PHP 7.1
$tmp = @mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
if ($tmp !== false)
{
$bytes = $tmp;
$hasBytes = true;
}
}
if ($hasBytes === false && file_exists('/dev/urandom') && is_readable('/dev/urandom') && (false !== ($fh = fopen('/dev/urandom', 'rb'))))
{
if (function_exists('stream_set_read_buffer'))
{
stream_set_read_buffer($fh, 0);
}
$tmp = fread($fh, $count);
fclose($fh);
if ($tmp !== false)
{
$bytes = $tmp;
$hasBytes = true;
}
}
/*
* We want to play it safe and disable openssl_random_pseudo_bytes() for now.
* This is due to the OpenSSL "PID wrapping bug", which potentially could affect GenPhrase.
*
if ($hasBytes === false && version_compare(PHP_VERSION, '5.3.4') >= 0 && function_exists('openssl_random_pseudo_bytes'))
{
$tmp = openssl_random_pseudo_bytes($count, $cryptoStrong);
if ($tmp !== false && $cryptoStrong === true)
{
$bytes = $tmp;
$hasBytes = true;
}
}
*/
if (isset($bytes[$count - 1]) && !isset($bytes[$count]))
{
return $bytes;
}
else
{
return false;
}
} | [
"public",
"function",
"getRandomBytes",
"(",
"$",
"count",
")",
"{",
"$",
"count",
"=",
"(",
"int",
")",
"$",
"count",
";",
"$",
"bytes",
"=",
"''",
";",
"$",
"hasBytes",
"=",
"false",
";",
"if",
"(",
"version_compare",
"(",
"PHP_VERSION",
",",
"'7.0.0'",
")",
">=",
"0",
"&&",
"function_exists",
"(",
"'random_bytes'",
")",
")",
"{",
"try",
"{",
"$",
"bytes",
"=",
"\\",
"random_bytes",
"(",
"$",
"count",
")",
";",
"$",
"hasBytes",
"=",
"true",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"//",
"}",
"}",
"// Make sure PHP version is at least 5.3. We do this because",
"// mcrypt_create_iv() on older versions of PHP",
"// does not give \"strong\" random data on Windows systems.",
"if",
"(",
"version_compare",
"(",
"PHP_VERSION",
",",
"'5.3.0'",
")",
">=",
"0",
"&&",
"function_exists",
"(",
"'mcrypt_create_iv'",
")",
")",
"{",
"// Suppress deprecation warning in PHP 7.1",
"$",
"tmp",
"=",
"@",
"mcrypt_create_iv",
"(",
"$",
"count",
",",
"MCRYPT_DEV_URANDOM",
")",
";",
"if",
"(",
"$",
"tmp",
"!==",
"false",
")",
"{",
"$",
"bytes",
"=",
"$",
"tmp",
";",
"$",
"hasBytes",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"$",
"hasBytes",
"===",
"false",
"&&",
"file_exists",
"(",
"'/dev/urandom'",
")",
"&&",
"is_readable",
"(",
"'/dev/urandom'",
")",
"&&",
"(",
"false",
"!==",
"(",
"$",
"fh",
"=",
"fopen",
"(",
"'/dev/urandom'",
",",
"'rb'",
")",
")",
")",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'stream_set_read_buffer'",
")",
")",
"{",
"stream_set_read_buffer",
"(",
"$",
"fh",
",",
"0",
")",
";",
"}",
"$",
"tmp",
"=",
"fread",
"(",
"$",
"fh",
",",
"$",
"count",
")",
";",
"fclose",
"(",
"$",
"fh",
")",
";",
"if",
"(",
"$",
"tmp",
"!==",
"false",
")",
"{",
"$",
"bytes",
"=",
"$",
"tmp",
";",
"$",
"hasBytes",
"=",
"true",
";",
"}",
"}",
"/*\n * We want to play it safe and disable openssl_random_pseudo_bytes() for now.\n * This is due to the OpenSSL \"PID wrapping bug\", which potentially could affect GenPhrase.\n *\n if ($hasBytes === false && version_compare(PHP_VERSION, '5.3.4') >= 0 && function_exists('openssl_random_pseudo_bytes'))\n {\n $tmp = openssl_random_pseudo_bytes($count, $cryptoStrong);\n if ($tmp !== false && $cryptoStrong === true)\n {\n $bytes = $tmp;\n $hasBytes = true;\n }\n }\n */",
"if",
"(",
"isset",
"(",
"$",
"bytes",
"[",
"$",
"count",
"-",
"1",
"]",
")",
"&&",
"!",
"isset",
"(",
"$",
"bytes",
"[",
"$",
"count",
"]",
")",
")",
"{",
"return",
"$",
"bytes",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
]
| Generate a random string of bytes.
@param int $count
@return string|boolean | [
"Generate",
"a",
"random",
"string",
"of",
"bytes",
"."
]
| 4b7e2b3ba6ce369b3a10e9c31e4e9dc63effe564 | https://github.com/timoh6/GenPhrase/blob/4b7e2b3ba6ce369b3a10e9c31e4e9dc63effe564/library/GenPhrase/Random/RandomBytes.php#L15-L87 | train |
pubsubhubbub/php-publisher | library/Publisher.php | Publisher.publish_update | public function publish_update($topic_urls, $http_function = false)
{
if (! isset($topic_urls)) {
throw new InvalidArgumentException('Please specify a topic url');
}
// check that we're working with an array
if (! is_array($topic_urls)) {
$topic_urls = [$topic_urls];
}
// set the mode to publish
$post_string = 'hub.mode=publish';
// loop through each topic url
foreach ($topic_urls as $topic_url) {
// lightweight check that we're actually working w/ a valid url
if (! preg_match('|^https?://|i', $topic_url)) {
throw new InvalidArgumentException('The specified topic url does not appear to be valid: ' . $topic_url);
}
// append the topic url parameters
$post_string .= '&hub.url=' . urlencode($topic_url);
}
// make the http post request and return true/false
// easy to over-write to use your own http function
if ($http_function) {
return $http_function($this->hub_url, $post_string);
}
return $this->http_post($this->hub_url, $post_string);
} | php | public function publish_update($topic_urls, $http_function = false)
{
if (! isset($topic_urls)) {
throw new InvalidArgumentException('Please specify a topic url');
}
// check that we're working with an array
if (! is_array($topic_urls)) {
$topic_urls = [$topic_urls];
}
// set the mode to publish
$post_string = 'hub.mode=publish';
// loop through each topic url
foreach ($topic_urls as $topic_url) {
// lightweight check that we're actually working w/ a valid url
if (! preg_match('|^https?://|i', $topic_url)) {
throw new InvalidArgumentException('The specified topic url does not appear to be valid: ' . $topic_url);
}
// append the topic url parameters
$post_string .= '&hub.url=' . urlencode($topic_url);
}
// make the http post request and return true/false
// easy to over-write to use your own http function
if ($http_function) {
return $http_function($this->hub_url, $post_string);
}
return $this->http_post($this->hub_url, $post_string);
} | [
"public",
"function",
"publish_update",
"(",
"$",
"topic_urls",
",",
"$",
"http_function",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"topic_urls",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Please specify a topic url'",
")",
";",
"}",
"// check that we're working with an array",
"if",
"(",
"!",
"is_array",
"(",
"$",
"topic_urls",
")",
")",
"{",
"$",
"topic_urls",
"=",
"[",
"$",
"topic_urls",
"]",
";",
"}",
"// set the mode to publish",
"$",
"post_string",
"=",
"'hub.mode=publish'",
";",
"// loop through each topic url",
"foreach",
"(",
"$",
"topic_urls",
"as",
"$",
"topic_url",
")",
"{",
"// lightweight check that we're actually working w/ a valid url",
"if",
"(",
"!",
"preg_match",
"(",
"'|^https?://|i'",
",",
"$",
"topic_url",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'The specified topic url does not appear to be valid: '",
".",
"$",
"topic_url",
")",
";",
"}",
"// append the topic url parameters",
"$",
"post_string",
".=",
"'&hub.url='",
".",
"urlencode",
"(",
"$",
"topic_url",
")",
";",
"}",
"// make the http post request and return true/false",
"// easy to over-write to use your own http function",
"if",
"(",
"$",
"http_function",
")",
"{",
"return",
"$",
"http_function",
"(",
"$",
"this",
"->",
"hub_url",
",",
"$",
"post_string",
")",
";",
"}",
"return",
"$",
"this",
"->",
"http_post",
"(",
"$",
"this",
"->",
"hub_url",
",",
"$",
"post_string",
")",
";",
"}"
]
| Accepts either a single url or an array of urls.
@param string|array $topic_urls
@param callable $http_function
@return mixed | [
"Accepts",
"either",
"a",
"single",
"url",
"or",
"an",
"array",
"of",
"urls",
"."
]
| 047b0faf6219071527a45942d6fef4dbc6d1d884 | https://github.com/pubsubhubbub/php-publisher/blob/047b0faf6219071527a45942d6fef4dbc6d1d884/library/Publisher.php#L52-L84 | train |
formapro/yadm | src/PessimisticLock.php | PessimisticLock.lock | public function lock(string $id, bool $blocking = true, int $limit = 300): void
{
$this->autoCreateIndexes && $this->createIndexes();
if ($limit > $this->limit) {
throw new \LogicException('The limit could not be greater than a default one. The default is used to set an expiration index');
}
$timeout = time() + $limit; // I think it must be a bit greater then mongos index ttl so there is a way to process data.
while (time() < $timeout) {
try {
$result = $this->collection->insertOne([
'id' => $id,
'timestamp' => new UTCDatetime(time() * 1000),
'sessionId' => $this->sessionId,
]);
if (false == $result->isAcknowledged()) {
throw new \LogicException(sprintf('Cannot obtain the lock for id %s. The insertOne operation is not acknowledged.', $id));
}
return;
} catch (BulkWriteException $e) {
} catch (DuplicateKeyException $e) {
// The lock is obtained by another process. Let's try again later.
}
if (false == $blocking) {
throw PessimisticLockException::failedObtainLock($id, $limit);
}
// Mongo does database lock level on insert, so everything has to wait even reads.
// I decided to do it rarely to decrease global lock rate.
// We will have at least 150 attempts to get the lock, pretty enough IMO.
// More here http://docs.mongodb.org/manual/faq/concurrency/
usleep(200000);
}
throw PessimisticLockException::failedObtainLock($id, $limit);
} | php | public function lock(string $id, bool $blocking = true, int $limit = 300): void
{
$this->autoCreateIndexes && $this->createIndexes();
if ($limit > $this->limit) {
throw new \LogicException('The limit could not be greater than a default one. The default is used to set an expiration index');
}
$timeout = time() + $limit; // I think it must be a bit greater then mongos index ttl so there is a way to process data.
while (time() < $timeout) {
try {
$result = $this->collection->insertOne([
'id' => $id,
'timestamp' => new UTCDatetime(time() * 1000),
'sessionId' => $this->sessionId,
]);
if (false == $result->isAcknowledged()) {
throw new \LogicException(sprintf('Cannot obtain the lock for id %s. The insertOne operation is not acknowledged.', $id));
}
return;
} catch (BulkWriteException $e) {
} catch (DuplicateKeyException $e) {
// The lock is obtained by another process. Let's try again later.
}
if (false == $blocking) {
throw PessimisticLockException::failedObtainLock($id, $limit);
}
// Mongo does database lock level on insert, so everything has to wait even reads.
// I decided to do it rarely to decrease global lock rate.
// We will have at least 150 attempts to get the lock, pretty enough IMO.
// More here http://docs.mongodb.org/manual/faq/concurrency/
usleep(200000);
}
throw PessimisticLockException::failedObtainLock($id, $limit);
} | [
"public",
"function",
"lock",
"(",
"string",
"$",
"id",
",",
"bool",
"$",
"blocking",
"=",
"true",
",",
"int",
"$",
"limit",
"=",
"300",
")",
":",
"void",
"{",
"$",
"this",
"->",
"autoCreateIndexes",
"&&",
"$",
"this",
"->",
"createIndexes",
"(",
")",
";",
"if",
"(",
"$",
"limit",
">",
"$",
"this",
"->",
"limit",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'The limit could not be greater than a default one. The default is used to set an expiration index'",
")",
";",
"}",
"$",
"timeout",
"=",
"time",
"(",
")",
"+",
"$",
"limit",
";",
"// I think it must be a bit greater then mongos index ttl so there is a way to process data.",
"while",
"(",
"time",
"(",
")",
"<",
"$",
"timeout",
")",
"{",
"try",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"collection",
"->",
"insertOne",
"(",
"[",
"'id'",
"=>",
"$",
"id",
",",
"'timestamp'",
"=>",
"new",
"UTCDatetime",
"(",
"time",
"(",
")",
"*",
"1000",
")",
",",
"'sessionId'",
"=>",
"$",
"this",
"->",
"sessionId",
",",
"]",
")",
";",
"if",
"(",
"false",
"==",
"$",
"result",
"->",
"isAcknowledged",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"sprintf",
"(",
"'Cannot obtain the lock for id %s. The insertOne operation is not acknowledged.'",
",",
"$",
"id",
")",
")",
";",
"}",
"return",
";",
"}",
"catch",
"(",
"BulkWriteException",
"$",
"e",
")",
"{",
"}",
"catch",
"(",
"DuplicateKeyException",
"$",
"e",
")",
"{",
"// The lock is obtained by another process. Let's try again later.",
"}",
"if",
"(",
"false",
"==",
"$",
"blocking",
")",
"{",
"throw",
"PessimisticLockException",
"::",
"failedObtainLock",
"(",
"$",
"id",
",",
"$",
"limit",
")",
";",
"}",
"// Mongo does database lock level on insert, so everything has to wait even reads.",
"// I decided to do it rarely to decrease global lock rate.",
"// We will have at least 150 attempts to get the lock, pretty enough IMO.",
"// More here http://docs.mongodb.org/manual/faq/concurrency/",
"usleep",
"(",
"200000",
")",
";",
"}",
"throw",
"PessimisticLockException",
"::",
"failedObtainLock",
"(",
"$",
"id",
",",
"$",
"limit",
")",
";",
"}"
]
| Limit is in seconds
@param string $id
@param bool $blocking
@param int $limit is ignored if blocking is false. | [
"Limit",
"is",
"in",
"seconds"
]
| f3fdb600adaaa2db4a8c9b3d58e8d009c3cbfbfc | https://github.com/formapro/yadm/blob/f3fdb600adaaa2db4a8c9b3d58e8d009c3cbfbfc/src/PessimisticLock.php#L61-L101 | train |
camunda/camunda-bpm-php-sdk | oop/main/helper/DiagramHelper.php | DiagramHelper.saveAsFile | public function saveAsFile($diagram, $savePath) {
if(is_dir($savePath)) {
$filePath = $savePath.'/'.$this->cleanFileName($diagram->id).'.bpmn';
} else {
$filePath = './'.$this->cleanFileName($diagram->id).'.bpmn';
}
$handle = fopen($filePath, 'c+');
ftruncate($handle, filesize($filePath));
fwrite($handle, $diagram->bpmn20Xml);
fclose($handle);
return $filePath;
} | php | public function saveAsFile($diagram, $savePath) {
if(is_dir($savePath)) {
$filePath = $savePath.'/'.$this->cleanFileName($diagram->id).'.bpmn';
} else {
$filePath = './'.$this->cleanFileName($diagram->id).'.bpmn';
}
$handle = fopen($filePath, 'c+');
ftruncate($handle, filesize($filePath));
fwrite($handle, $diagram->bpmn20Xml);
fclose($handle);
return $filePath;
} | [
"public",
"function",
"saveAsFile",
"(",
"$",
"diagram",
",",
"$",
"savePath",
")",
"{",
"if",
"(",
"is_dir",
"(",
"$",
"savePath",
")",
")",
"{",
"$",
"filePath",
"=",
"$",
"savePath",
".",
"'/'",
".",
"$",
"this",
"->",
"cleanFileName",
"(",
"$",
"diagram",
"->",
"id",
")",
".",
"'.bpmn'",
";",
"}",
"else",
"{",
"$",
"filePath",
"=",
"'./'",
".",
"$",
"this",
"->",
"cleanFileName",
"(",
"$",
"diagram",
"->",
"id",
")",
".",
"'.bpmn'",
";",
"}",
"$",
"handle",
"=",
"fopen",
"(",
"$",
"filePath",
",",
"'c+'",
")",
";",
"ftruncate",
"(",
"$",
"handle",
",",
"filesize",
"(",
"$",
"filePath",
")",
")",
";",
"fwrite",
"(",
"$",
"handle",
",",
"$",
"diagram",
"->",
"bpmn20Xml",
")",
";",
"fclose",
"(",
"$",
"handle",
")",
";",
"return",
"$",
"filePath",
";",
"}"
]
| saves the bpmn diagram as file.
@param $diagram
@param $savePath
@return string | [
"saves",
"the",
"bpmn",
"diagram",
"as",
"file",
"."
]
| be617b6f9d0eccf266a1f1f51406c0a28cae4c1f | https://github.com/camunda/camunda-bpm-php-sdk/blob/be617b6f9d0eccf266a1f1f51406c0a28cae4c1f/oop/main/helper/DiagramHelper.php#L21-L34 | train |
AcuityScheduling/acuity-php | src/AcuityScheduling.php | AcuityScheduling.verifyMessageSignature | public static function verifyMessageSignature($secret, $body = null, $signature = null) {
// Compute hash of message using shared secret:
$body = is_null($body) ? file_get_contents('php://input') : $body;
$hash = base64_encode(hash_hmac('sha256', $body, $secret, true));
// Compare hash to the signature:
$signature = is_null($signature) ? $_SERVER['HTTP_X_ACUITY_SIGNATURE'] : $signature;
if ($hash !== $signature) {
throw new Exception('This message was forged!');
}
} | php | public static function verifyMessageSignature($secret, $body = null, $signature = null) {
// Compute hash of message using shared secret:
$body = is_null($body) ? file_get_contents('php://input') : $body;
$hash = base64_encode(hash_hmac('sha256', $body, $secret, true));
// Compare hash to the signature:
$signature = is_null($signature) ? $_SERVER['HTTP_X_ACUITY_SIGNATURE'] : $signature;
if ($hash !== $signature) {
throw new Exception('This message was forged!');
}
} | [
"public",
"static",
"function",
"verifyMessageSignature",
"(",
"$",
"secret",
",",
"$",
"body",
"=",
"null",
",",
"$",
"signature",
"=",
"null",
")",
"{",
"// Compute hash of message using shared secret:",
"$",
"body",
"=",
"is_null",
"(",
"$",
"body",
")",
"?",
"file_get_contents",
"(",
"'php://input'",
")",
":",
"$",
"body",
";",
"$",
"hash",
"=",
"base64_encode",
"(",
"hash_hmac",
"(",
"'sha256'",
",",
"$",
"body",
",",
"$",
"secret",
",",
"true",
")",
")",
";",
"// Compare hash to the signature:",
"$",
"signature",
"=",
"is_null",
"(",
"$",
"signature",
")",
"?",
"$",
"_SERVER",
"[",
"'HTTP_X_ACUITY_SIGNATURE'",
"]",
":",
"$",
"signature",
";",
"if",
"(",
"$",
"hash",
"!==",
"$",
"signature",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'This message was forged!'",
")",
";",
"}",
"}"
]
| Verify a message signature using your API key. | [
"Verify",
"a",
"message",
"signature",
"using",
"your",
"API",
"key",
"."
]
| e0810aabc571b10895bac52a597412286c02bc3d | https://github.com/AcuityScheduling/acuity-php/blob/e0810aabc571b10895bac52a597412286c02bc3d/src/AcuityScheduling.php#L128-L139 | train |
skaut/Skautis | src/HelperTrait.php | HelperTrait.getInstance | public static function getInstance($appId, $testMode = false, $cache = false, $compression = false)
{
if (!isset(self::$instances[$appId])) {
$config = new Config($appId);
$config->setTestMode($testMode);
$config->setCache($cache);
$config->setCompression($compression);
$webServiceFactory = new WebServiceFactory();
$wsdlManager = new WsdlManager($webServiceFactory, $config);
// Out of box integrace s $_SESSION
$sessionAdapter = new SessionAdapter();
$user = new User($wsdlManager, $sessionAdapter);
self::$instances[$appId] = new self($wsdlManager, $user);
}
return self::$instances[$appId];
} | php | public static function getInstance($appId, $testMode = false, $cache = false, $compression = false)
{
if (!isset(self::$instances[$appId])) {
$config = new Config($appId);
$config->setTestMode($testMode);
$config->setCache($cache);
$config->setCompression($compression);
$webServiceFactory = new WebServiceFactory();
$wsdlManager = new WsdlManager($webServiceFactory, $config);
// Out of box integrace s $_SESSION
$sessionAdapter = new SessionAdapter();
$user = new User($wsdlManager, $sessionAdapter);
self::$instances[$appId] = new self($wsdlManager, $user);
}
return self::$instances[$appId];
} | [
"public",
"static",
"function",
"getInstance",
"(",
"$",
"appId",
",",
"$",
"testMode",
"=",
"false",
",",
"$",
"cache",
"=",
"false",
",",
"$",
"compression",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"instances",
"[",
"$",
"appId",
"]",
")",
")",
"{",
"$",
"config",
"=",
"new",
"Config",
"(",
"$",
"appId",
")",
";",
"$",
"config",
"->",
"setTestMode",
"(",
"$",
"testMode",
")",
";",
"$",
"config",
"->",
"setCache",
"(",
"$",
"cache",
")",
";",
"$",
"config",
"->",
"setCompression",
"(",
"$",
"compression",
")",
";",
"$",
"webServiceFactory",
"=",
"new",
"WebServiceFactory",
"(",
")",
";",
"$",
"wsdlManager",
"=",
"new",
"WsdlManager",
"(",
"$",
"webServiceFactory",
",",
"$",
"config",
")",
";",
"// Out of box integrace s $_SESSION",
"$",
"sessionAdapter",
"=",
"new",
"SessionAdapter",
"(",
")",
";",
"$",
"user",
"=",
"new",
"User",
"(",
"$",
"wsdlManager",
",",
"$",
"sessionAdapter",
")",
";",
"self",
"::",
"$",
"instances",
"[",
"$",
"appId",
"]",
"=",
"new",
"self",
"(",
"$",
"wsdlManager",
",",
"$",
"user",
")",
";",
"}",
"return",
"self",
"::",
"$",
"instances",
"[",
"$",
"appId",
"]",
";",
"}"
]
| Ziska sdilenou instanci Skautis objektu
Ano vime ze to neni officialni pattern
Jedna se o kockopsa Mezi singletonem a StaticFactory
Factory metoda na stride kterou instantizuje a novy objekt vytvari jen 1x za beh
Proc to tak je? Ohled na zpetnou kompatibilitu a out of the box pouzitelnost pro amatery
@var string $appId nastavení appId (nepovinné)
@var bool $testMode funguje v testovacím provozu? - výchozí je testovací mode (nepovinné)
@return Skautis Sdilena instance Skautis knihovny pro cely beh PHP skriptu | [
"Ziska",
"sdilenou",
"instanci",
"Skautis",
"objektu"
]
| 634ac3a978c1b1f88c20b67bfdeba099a5102d95 | https://github.com/skaut/Skautis/blob/634ac3a978c1b1f88c20b67bfdeba099a5102d95/src/HelperTrait.php#L33-L52 | train |
skaut/Skautis | src/SkautisQuery.php | SkautisQuery.done | public function done($result = null, \Exception $e = null)
{
$this->time += microtime(true);
$this->result = $result;
$this->exception = $e;
return $this;
} | php | public function done($result = null, \Exception $e = null)
{
$this->time += microtime(true);
$this->result = $result;
$this->exception = $e;
return $this;
} | [
"public",
"function",
"done",
"(",
"$",
"result",
"=",
"null",
",",
"\\",
"Exception",
"$",
"e",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"time",
"+=",
"microtime",
"(",
"true",
")",
";",
"$",
"this",
"->",
"result",
"=",
"$",
"result",
";",
"$",
"this",
"->",
"exception",
"=",
"$",
"e",
";",
"return",
"$",
"this",
";",
"}"
]
| Oznac pozadavek za dokonceny a uloz vysledek
@param mixed $result Odpoved ze serveru
@param \Exception Výjimka v pripade problemu | [
"Oznac",
"pozadavek",
"za",
"dokonceny",
"a",
"uloz",
"vysledek"
]
| 634ac3a978c1b1f88c20b67bfdeba099a5102d95 | https://github.com/skaut/Skautis/blob/634ac3a978c1b1f88c20b67bfdeba099a5102d95/src/SkautisQuery.php#L105-L112 | train |
chadicus/slim-oauth2-http | src/RequestBridge.php | RequestBridge.toOAuth2 | final public static function toOAuth2(ServerRequestInterface $request)
{
$contents = $request->getBody()->getContents();
$request->getBody()->rewind();
return new OAuth2\Request(
(array)$request->getQueryParams(),
(array)$request->getParsedBody(),
$request->getAttributes(),
$request->getCookieParams(),
self::convertUploadedFiles($request->getUploadedFiles()),
$request->getServerParams(),
$contents,
self::cleanupHeaders($request->getHeaders())
);
} | php | final public static function toOAuth2(ServerRequestInterface $request)
{
$contents = $request->getBody()->getContents();
$request->getBody()->rewind();
return new OAuth2\Request(
(array)$request->getQueryParams(),
(array)$request->getParsedBody(),
$request->getAttributes(),
$request->getCookieParams(),
self::convertUploadedFiles($request->getUploadedFiles()),
$request->getServerParams(),
$contents,
self::cleanupHeaders($request->getHeaders())
);
} | [
"final",
"public",
"static",
"function",
"toOAuth2",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"$",
"contents",
"=",
"$",
"request",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
";",
"$",
"request",
"->",
"getBody",
"(",
")",
"->",
"rewind",
"(",
")",
";",
"return",
"new",
"OAuth2",
"\\",
"Request",
"(",
"(",
"array",
")",
"$",
"request",
"->",
"getQueryParams",
"(",
")",
",",
"(",
"array",
")",
"$",
"request",
"->",
"getParsedBody",
"(",
")",
",",
"$",
"request",
"->",
"getAttributes",
"(",
")",
",",
"$",
"request",
"->",
"getCookieParams",
"(",
")",
",",
"self",
"::",
"convertUploadedFiles",
"(",
"$",
"request",
"->",
"getUploadedFiles",
"(",
")",
")",
",",
"$",
"request",
"->",
"getServerParams",
"(",
")",
",",
"$",
"contents",
",",
"self",
"::",
"cleanupHeaders",
"(",
"$",
"request",
"->",
"getHeaders",
"(",
")",
")",
")",
";",
"}"
]
| Returns a new instance of \OAuth2\Request based on the given \Slim\Http\Request
@param ServerRequestInterface $request The psr-7 request.
@return OAuth2\Request | [
"Returns",
"a",
"new",
"instance",
"of",
"\\",
"OAuth2",
"\\",
"Request",
"based",
"on",
"the",
"given",
"\\",
"Slim",
"\\",
"Http",
"\\",
"Request"
]
| 4c2bb3af076f2ac7b74f914dcaf446fa1025b97a | https://github.com/chadicus/slim-oauth2-http/blob/4c2bb3af076f2ac7b74f914dcaf446fa1025b97a/src/RequestBridge.php#L20-L35 | train |
chadicus/slim-oauth2-http | src/RequestBridge.php | RequestBridge.cleanupHeaders | private static function cleanupHeaders(array $uncleanHeaders = [])
{
$cleanHeaders = [];
$headerMap = [
'Php-Auth-User' => 'PHP_AUTH_USER',
'Php-Auth-Pw' => 'PHP_AUTH_PW',
'Php-Auth-Digest' => 'PHP_AUTH_DIGEST',
'Auth-Type' => 'AUTH_TYPE',
'HTTP_AUTHORIZATION' => 'AUTHORIZATION',
];
foreach ($uncleanHeaders as $key => $value) {
if (array_key_exists($key, $headerMap)) {
$key = $headerMap[$key];
}
$cleanHeaders[$key] = is_array($value) ? implode(', ', $value) : $value;
}
return $cleanHeaders;
} | php | private static function cleanupHeaders(array $uncleanHeaders = [])
{
$cleanHeaders = [];
$headerMap = [
'Php-Auth-User' => 'PHP_AUTH_USER',
'Php-Auth-Pw' => 'PHP_AUTH_PW',
'Php-Auth-Digest' => 'PHP_AUTH_DIGEST',
'Auth-Type' => 'AUTH_TYPE',
'HTTP_AUTHORIZATION' => 'AUTHORIZATION',
];
foreach ($uncleanHeaders as $key => $value) {
if (array_key_exists($key, $headerMap)) {
$key = $headerMap[$key];
}
$cleanHeaders[$key] = is_array($value) ? implode(', ', $value) : $value;
}
return $cleanHeaders;
} | [
"private",
"static",
"function",
"cleanupHeaders",
"(",
"array",
"$",
"uncleanHeaders",
"=",
"[",
"]",
")",
"{",
"$",
"cleanHeaders",
"=",
"[",
"]",
";",
"$",
"headerMap",
"=",
"[",
"'Php-Auth-User'",
"=>",
"'PHP_AUTH_USER'",
",",
"'Php-Auth-Pw'",
"=>",
"'PHP_AUTH_PW'",
",",
"'Php-Auth-Digest'",
"=>",
"'PHP_AUTH_DIGEST'",
",",
"'Auth-Type'",
"=>",
"'AUTH_TYPE'",
",",
"'HTTP_AUTHORIZATION'",
"=>",
"'AUTHORIZATION'",
",",
"]",
";",
"foreach",
"(",
"$",
"uncleanHeaders",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"headerMap",
")",
")",
"{",
"$",
"key",
"=",
"$",
"headerMap",
"[",
"$",
"key",
"]",
";",
"}",
"$",
"cleanHeaders",
"[",
"$",
"key",
"]",
"=",
"is_array",
"(",
"$",
"value",
")",
"?",
"implode",
"(",
"', '",
",",
"$",
"value",
")",
":",
"$",
"value",
";",
"}",
"return",
"$",
"cleanHeaders",
";",
"}"
]
| Helper method to clean header keys and values.
Slim will convert all headers to Camel-Case style. There are certain headers such as PHP_AUTH_USER that the
OAuth2 library requires CAPS_CASE format. This method will adjust those headers as needed. The OAuth2 library
also does not expect arrays for header values, this method will implode the multiple values with a ', '
@param array $uncleanHeaders The headers to be cleaned.
@return array The cleaned headers | [
"Helper",
"method",
"to",
"clean",
"header",
"keys",
"and",
"values",
"."
]
| 4c2bb3af076f2ac7b74f914dcaf446fa1025b97a | https://github.com/chadicus/slim-oauth2-http/blob/4c2bb3af076f2ac7b74f914dcaf446fa1025b97a/src/RequestBridge.php#L48-L68 | train |
chadicus/slim-oauth2-http | src/ResponseBridge.php | ResponseBridge.fromOauth2 | final public static function fromOauth2(OAuth2\Response $oauth2Response)
{
$headers = [];
foreach ($oauth2Response->getHttpHeaders() as $key => $value) {
$headers[$key] = explode(', ', $value);
}
$stream = fopen('php://temp', 'r+');
if (!empty($oauth2Response->getParameters())) {
fwrite($stream, $oauth2Response->getResponseBody());
rewind($stream);
}
return new Response(new Stream($stream), $oauth2Response->getStatusCode(), $headers);
} | php | final public static function fromOauth2(OAuth2\Response $oauth2Response)
{
$headers = [];
foreach ($oauth2Response->getHttpHeaders() as $key => $value) {
$headers[$key] = explode(', ', $value);
}
$stream = fopen('php://temp', 'r+');
if (!empty($oauth2Response->getParameters())) {
fwrite($stream, $oauth2Response->getResponseBody());
rewind($stream);
}
return new Response(new Stream($stream), $oauth2Response->getStatusCode(), $headers);
} | [
"final",
"public",
"static",
"function",
"fromOauth2",
"(",
"OAuth2",
"\\",
"Response",
"$",
"oauth2Response",
")",
"{",
"$",
"headers",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"oauth2Response",
"->",
"getHttpHeaders",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"headers",
"[",
"$",
"key",
"]",
"=",
"explode",
"(",
"', '",
",",
"$",
"value",
")",
";",
"}",
"$",
"stream",
"=",
"fopen",
"(",
"'php://temp'",
",",
"'r+'",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"oauth2Response",
"->",
"getParameters",
"(",
")",
")",
")",
"{",
"fwrite",
"(",
"$",
"stream",
",",
"$",
"oauth2Response",
"->",
"getResponseBody",
"(",
")",
")",
";",
"rewind",
"(",
"$",
"stream",
")",
";",
"}",
"return",
"new",
"Response",
"(",
"new",
"Stream",
"(",
"$",
"stream",
")",
",",
"$",
"oauth2Response",
"->",
"getStatusCode",
"(",
")",
",",
"$",
"headers",
")",
";",
"}"
]
| Copies values from the given Oauth2\Response to a PSR-7 Http Response.
@param OAuth2\Response $oauth2Response The OAuth2 server response.
@return \Psr\Http\Message\ResponseInterface | [
"Copies",
"values",
"from",
"the",
"given",
"Oauth2",
"\\",
"Response",
"to",
"a",
"PSR",
"-",
"7",
"Http",
"Response",
"."
]
| 4c2bb3af076f2ac7b74f914dcaf446fa1025b97a | https://github.com/chadicus/slim-oauth2-http/blob/4c2bb3af076f2ac7b74f914dcaf446fa1025b97a/src/ResponseBridge.php#L20-L34 | train |
matomo-org/component-network | src/IPUtils.php | IPUtils.sanitizeIp | public static function sanitizeIp($ipString)
{
$ipString = trim($ipString);
// CIDR notation, A.B.C.D/E
$posSlash = strrpos($ipString, '/');
if ($posSlash !== false) {
$ipString = substr($ipString, 0, $posSlash);
}
$posColon = strrpos($ipString, ':');
$posDot = strrpos($ipString, '.');
if ($posColon !== false) {
// IPv6 address with port, [A:B:C:D:E:F:G:H]:EEEE
$posRBrac = strrpos($ipString, ']');
if ($posRBrac !== false && $ipString[0] == '[') {
$ipString = substr($ipString, 1, $posRBrac - 1);
}
if ($posDot !== false) {
// IPv4 address with port, A.B.C.D:EEEE
if ($posColon > $posDot) {
$ipString = substr($ipString, 0, $posColon);
}
// else: Dotted quad IPv6 address, A:B:C:D:E:F:G.H.I.J
} else if (strpos($ipString, ':') === $posColon) {
$ipString = substr($ipString, 0, $posColon);
}
// else: IPv6 address, A:B:C:D:E:F:G:H
}
// else: IPv4 address, A.B.C.D
return $ipString;
} | php | public static function sanitizeIp($ipString)
{
$ipString = trim($ipString);
// CIDR notation, A.B.C.D/E
$posSlash = strrpos($ipString, '/');
if ($posSlash !== false) {
$ipString = substr($ipString, 0, $posSlash);
}
$posColon = strrpos($ipString, ':');
$posDot = strrpos($ipString, '.');
if ($posColon !== false) {
// IPv6 address with port, [A:B:C:D:E:F:G:H]:EEEE
$posRBrac = strrpos($ipString, ']');
if ($posRBrac !== false && $ipString[0] == '[') {
$ipString = substr($ipString, 1, $posRBrac - 1);
}
if ($posDot !== false) {
// IPv4 address with port, A.B.C.D:EEEE
if ($posColon > $posDot) {
$ipString = substr($ipString, 0, $posColon);
}
// else: Dotted quad IPv6 address, A:B:C:D:E:F:G.H.I.J
} else if (strpos($ipString, ':') === $posColon) {
$ipString = substr($ipString, 0, $posColon);
}
// else: IPv6 address, A:B:C:D:E:F:G:H
}
// else: IPv4 address, A.B.C.D
return $ipString;
} | [
"public",
"static",
"function",
"sanitizeIp",
"(",
"$",
"ipString",
")",
"{",
"$",
"ipString",
"=",
"trim",
"(",
"$",
"ipString",
")",
";",
"// CIDR notation, A.B.C.D/E",
"$",
"posSlash",
"=",
"strrpos",
"(",
"$",
"ipString",
",",
"'/'",
")",
";",
"if",
"(",
"$",
"posSlash",
"!==",
"false",
")",
"{",
"$",
"ipString",
"=",
"substr",
"(",
"$",
"ipString",
",",
"0",
",",
"$",
"posSlash",
")",
";",
"}",
"$",
"posColon",
"=",
"strrpos",
"(",
"$",
"ipString",
",",
"':'",
")",
";",
"$",
"posDot",
"=",
"strrpos",
"(",
"$",
"ipString",
",",
"'.'",
")",
";",
"if",
"(",
"$",
"posColon",
"!==",
"false",
")",
"{",
"// IPv6 address with port, [A:B:C:D:E:F:G:H]:EEEE",
"$",
"posRBrac",
"=",
"strrpos",
"(",
"$",
"ipString",
",",
"']'",
")",
";",
"if",
"(",
"$",
"posRBrac",
"!==",
"false",
"&&",
"$",
"ipString",
"[",
"0",
"]",
"==",
"'['",
")",
"{",
"$",
"ipString",
"=",
"substr",
"(",
"$",
"ipString",
",",
"1",
",",
"$",
"posRBrac",
"-",
"1",
")",
";",
"}",
"if",
"(",
"$",
"posDot",
"!==",
"false",
")",
"{",
"// IPv4 address with port, A.B.C.D:EEEE",
"if",
"(",
"$",
"posColon",
">",
"$",
"posDot",
")",
"{",
"$",
"ipString",
"=",
"substr",
"(",
"$",
"ipString",
",",
"0",
",",
"$",
"posColon",
")",
";",
"}",
"// else: Dotted quad IPv6 address, A:B:C:D:E:F:G.H.I.J",
"}",
"else",
"if",
"(",
"strpos",
"(",
"$",
"ipString",
",",
"':'",
")",
"===",
"$",
"posColon",
")",
"{",
"$",
"ipString",
"=",
"substr",
"(",
"$",
"ipString",
",",
"0",
",",
"$",
"posColon",
")",
";",
"}",
"// else: IPv6 address, A:B:C:D:E:F:G:H",
"}",
"// else: IPv4 address, A.B.C.D",
"return",
"$",
"ipString",
";",
"}"
]
| Removes the port and the last portion of a CIDR IP address.
@param string $ipString The IP address to sanitize.
@return string | [
"Removes",
"the",
"port",
"and",
"the",
"last",
"portion",
"of",
"a",
"CIDR",
"IP",
"address",
"."
]
| f54c1027bb04c1393ccea275b44eee1262b46c46 | https://github.com/matomo-org/component-network/blob/f54c1027bb04c1393ccea275b44eee1262b46c46/src/IPUtils.php#L25-L58 | train |
matomo-org/component-network | src/IPUtils.php | IPUtils.getIPRangeBounds | public static function getIPRangeBounds($ipRange)
{
if (strpos($ipRange, '/') === false) {
$ipRange = self::sanitizeIpRange($ipRange);
if ($ipRange === null) {
return null;
}
}
$pos = strpos($ipRange, '/');
$bits = substr($ipRange, $pos + 1);
$range = substr($ipRange, 0, $pos);
$high = $low = @inet_pton($range);
if ($low === false) {
return null;
}
$lowLen = strlen($low);
$i = $lowLen - 1;
$bits = $lowLen * 8 - $bits;
for ($n = (int)($bits / 8); $n > 0; $n--, $i--) {
$low[$i] = chr(0);
$high[$i] = chr(255);
}
$n = $bits % 8;
if ($n) {
$low[$i] = chr(ord($low[$i]) & ~((1 << $n) - 1));
$high[$i] = chr(ord($high[$i]) | ((1 << $n) - 1));
}
return array($low, $high);
} | php | public static function getIPRangeBounds($ipRange)
{
if (strpos($ipRange, '/') === false) {
$ipRange = self::sanitizeIpRange($ipRange);
if ($ipRange === null) {
return null;
}
}
$pos = strpos($ipRange, '/');
$bits = substr($ipRange, $pos + 1);
$range = substr($ipRange, 0, $pos);
$high = $low = @inet_pton($range);
if ($low === false) {
return null;
}
$lowLen = strlen($low);
$i = $lowLen - 1;
$bits = $lowLen * 8 - $bits;
for ($n = (int)($bits / 8); $n > 0; $n--, $i--) {
$low[$i] = chr(0);
$high[$i] = chr(255);
}
$n = $bits % 8;
if ($n) {
$low[$i] = chr(ord($low[$i]) & ~((1 << $n) - 1));
$high[$i] = chr(ord($high[$i]) | ((1 << $n) - 1));
}
return array($low, $high);
} | [
"public",
"static",
"function",
"getIPRangeBounds",
"(",
"$",
"ipRange",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"ipRange",
",",
"'/'",
")",
"===",
"false",
")",
"{",
"$",
"ipRange",
"=",
"self",
"::",
"sanitizeIpRange",
"(",
"$",
"ipRange",
")",
";",
"if",
"(",
"$",
"ipRange",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"}",
"$",
"pos",
"=",
"strpos",
"(",
"$",
"ipRange",
",",
"'/'",
")",
";",
"$",
"bits",
"=",
"substr",
"(",
"$",
"ipRange",
",",
"$",
"pos",
"+",
"1",
")",
";",
"$",
"range",
"=",
"substr",
"(",
"$",
"ipRange",
",",
"0",
",",
"$",
"pos",
")",
";",
"$",
"high",
"=",
"$",
"low",
"=",
"@",
"inet_pton",
"(",
"$",
"range",
")",
";",
"if",
"(",
"$",
"low",
"===",
"false",
")",
"{",
"return",
"null",
";",
"}",
"$",
"lowLen",
"=",
"strlen",
"(",
"$",
"low",
")",
";",
"$",
"i",
"=",
"$",
"lowLen",
"-",
"1",
";",
"$",
"bits",
"=",
"$",
"lowLen",
"*",
"8",
"-",
"$",
"bits",
";",
"for",
"(",
"$",
"n",
"=",
"(",
"int",
")",
"(",
"$",
"bits",
"/",
"8",
")",
";",
"$",
"n",
">",
"0",
";",
"$",
"n",
"--",
",",
"$",
"i",
"--",
")",
"{",
"$",
"low",
"[",
"$",
"i",
"]",
"=",
"chr",
"(",
"0",
")",
";",
"$",
"high",
"[",
"$",
"i",
"]",
"=",
"chr",
"(",
"255",
")",
";",
"}",
"$",
"n",
"=",
"$",
"bits",
"%",
"8",
";",
"if",
"(",
"$",
"n",
")",
"{",
"$",
"low",
"[",
"$",
"i",
"]",
"=",
"chr",
"(",
"ord",
"(",
"$",
"low",
"[",
"$",
"i",
"]",
")",
"&",
"~",
"(",
"(",
"1",
"<<",
"$",
"n",
")",
"-",
"1",
")",
")",
";",
"$",
"high",
"[",
"$",
"i",
"]",
"=",
"chr",
"(",
"ord",
"(",
"$",
"high",
"[",
"$",
"i",
"]",
")",
"|",
"(",
"(",
"1",
"<<",
"$",
"n",
")",
"-",
"1",
")",
")",
";",
"}",
"return",
"array",
"(",
"$",
"low",
",",
"$",
"high",
")",
";",
"}"
]
| Get low and high IP addresses for a specified IP range.
@param string $ipRange An IP address range in string format, e.g. `'192.168.1.1/24'`.
@return array|null Array `array($lowIp, $highIp)` in binary format, or null on failure. | [
"Get",
"low",
"and",
"high",
"IP",
"addresses",
"for",
"a",
"specified",
"IP",
"range",
"."
]
| f54c1027bb04c1393ccea275b44eee1262b46c46 | https://github.com/matomo-org/component-network/blob/f54c1027bb04c1393ccea275b44eee1262b46c46/src/IPUtils.php#L153-L187 | train |
matomo-org/component-network | src/IP.php | IP.fromBinaryIP | public static function fromBinaryIP($ip)
{
if ($ip === null || $ip === '') {
return new IPv4("\x00\x00\x00\x00");
}
if (self::isIPv4($ip)) {
return new IPv4($ip);
}
return new IPv6($ip);
} | php | public static function fromBinaryIP($ip)
{
if ($ip === null || $ip === '') {
return new IPv4("\x00\x00\x00\x00");
}
if (self::isIPv4($ip)) {
return new IPv4($ip);
}
return new IPv6($ip);
} | [
"public",
"static",
"function",
"fromBinaryIP",
"(",
"$",
"ip",
")",
"{",
"if",
"(",
"$",
"ip",
"===",
"null",
"||",
"$",
"ip",
"===",
"''",
")",
"{",
"return",
"new",
"IPv4",
"(",
"\"\\x00\\x00\\x00\\x00\"",
")",
";",
"}",
"if",
"(",
"self",
"::",
"isIPv4",
"(",
"$",
"ip",
")",
")",
"{",
"return",
"new",
"IPv4",
"(",
"$",
"ip",
")",
";",
"}",
"return",
"new",
"IPv6",
"(",
"$",
"ip",
")",
";",
"}"
]
| Factory method to create an IP instance from an IP in binary format.
@see fromStringIP
@param string $ip IP address in a binary format.
@return IP | [
"Factory",
"method",
"to",
"create",
"an",
"IP",
"instance",
"from",
"an",
"IP",
"in",
"binary",
"format",
"."
]
| f54c1027bb04c1393ccea275b44eee1262b46c46 | https://github.com/matomo-org/component-network/blob/f54c1027bb04c1393ccea275b44eee1262b46c46/src/IP.php#L45-L56 | train |
matomo-org/component-network | src/IP.php | IP.getHostname | public function getHostname()
{
$stringIp = $this->toString();
$host = strtolower(@gethostbyaddr($stringIp));
if ($host === '' || $host === $stringIp) {
return null;
}
return $host;
} | php | public function getHostname()
{
$stringIp = $this->toString();
$host = strtolower(@gethostbyaddr($stringIp));
if ($host === '' || $host === $stringIp) {
return null;
}
return $host;
} | [
"public",
"function",
"getHostname",
"(",
")",
"{",
"$",
"stringIp",
"=",
"$",
"this",
"->",
"toString",
"(",
")",
";",
"$",
"host",
"=",
"strtolower",
"(",
"@",
"gethostbyaddr",
"(",
"$",
"stringIp",
")",
")",
";",
"if",
"(",
"$",
"host",
"===",
"''",
"||",
"$",
"host",
"===",
"$",
"stringIp",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"host",
";",
"}"
]
| Tries to return the hostname associated to the IP.
@return string|null The hostname or null if the hostname can't be resolved. | [
"Tries",
"to",
"return",
"the",
"hostname",
"associated",
"to",
"the",
"IP",
"."
]
| f54c1027bb04c1393ccea275b44eee1262b46c46 | https://github.com/matomo-org/component-network/blob/f54c1027bb04c1393ccea275b44eee1262b46c46/src/IP.php#L104-L115 | train |
donquixote/cellbrush | src/Matrix/CellMatrix.php | CellMatrix.renderAsTable | public function renderAsTable() {
$html = '';
foreach ($this->cells as $iRow => $rowCells) {
$rowHtml = '';
foreach ($rowCells as $iCol => $cell) {
$rowHtml .= $cell->render();
}
$html .= ' <tr>' . $rowHtml . '</tr>' . "\n";
}
return "<table>\n <tbody>\n" . $html . " </tbody>\n</table>\n";
} | php | public function renderAsTable() {
$html = '';
foreach ($this->cells as $iRow => $rowCells) {
$rowHtml = '';
foreach ($rowCells as $iCol => $cell) {
$rowHtml .= $cell->render();
}
$html .= ' <tr>' . $rowHtml . '</tr>' . "\n";
}
return "<table>\n <tbody>\n" . $html . " </tbody>\n</table>\n";
} | [
"public",
"function",
"renderAsTable",
"(",
")",
"{",
"$",
"html",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"cells",
"as",
"$",
"iRow",
"=>",
"$",
"rowCells",
")",
"{",
"$",
"rowHtml",
"=",
"''",
";",
"foreach",
"(",
"$",
"rowCells",
"as",
"$",
"iCol",
"=>",
"$",
"cell",
")",
"{",
"$",
"rowHtml",
".=",
"$",
"cell",
"->",
"render",
"(",
")",
";",
"}",
"$",
"html",
".=",
"' <tr>'",
".",
"$",
"rowHtml",
".",
"'</tr>'",
".",
"\"\\n\"",
";",
"}",
"return",
"\"<table>\\n <tbody>\\n\"",
".",
"$",
"html",
".",
"\" </tbody>\\n</table>\\n\"",
";",
"}"
]
| Renders the inner html of the table section.
This is only used for testing.
@return string
The inner html of a table section. | [
"Renders",
"the",
"inner",
"html",
"of",
"the",
"table",
"section",
"."
]
| 09c70b421828624756e56591de41d5e86030f50e | https://github.com/donquixote/cellbrush/blob/09c70b421828624756e56591de41d5e86030f50e/src/Matrix/CellMatrix.php#L174-L184 | train |
donquixote/cellbrush | src/MiniContainer/MiniContainerBase.php | MiniContainerBase.validate | protected function validate($key, $value) {
if (!isset($this->defaults[$key])) {
$factory_method = 'get_' . $key;
if (!method_exists($this, $factory_method)) {
// Keys are only 'known' if there is a get_ method.
throw new MiniContainerException(sprintf('Unknown key "%s"', $key));
}
}
$validate_method = 'validate_' . $key;
if (!method_exists($this, $validate_method)) {
// Keys can only be initialized if there is a validate method.
throw new MiniContainerException(sprintf('Key "%s" is known, but has no validate method.', $key));
}
$this->$validate_method($value);
} | php | protected function validate($key, $value) {
if (!isset($this->defaults[$key])) {
$factory_method = 'get_' . $key;
if (!method_exists($this, $factory_method)) {
// Keys are only 'known' if there is a get_ method.
throw new MiniContainerException(sprintf('Unknown key "%s"', $key));
}
}
$validate_method = 'validate_' . $key;
if (!method_exists($this, $validate_method)) {
// Keys can only be initialized if there is a validate method.
throw new MiniContainerException(sprintf('Key "%s" is known, but has no validate method.', $key));
}
$this->$validate_method($value);
} | [
"protected",
"function",
"validate",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"defaults",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"factory_method",
"=",
"'get_'",
".",
"$",
"key",
";",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"this",
",",
"$",
"factory_method",
")",
")",
"{",
"// Keys are only 'known' if there is a get_ method.",
"throw",
"new",
"MiniContainerException",
"(",
"sprintf",
"(",
"'Unknown key \"%s\"'",
",",
"$",
"key",
")",
")",
";",
"}",
"}",
"$",
"validate_method",
"=",
"'validate_'",
".",
"$",
"key",
";",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"this",
",",
"$",
"validate_method",
")",
")",
"{",
"// Keys can only be initialized if there is a validate method.",
"throw",
"new",
"MiniContainerException",
"(",
"sprintf",
"(",
"'Key \"%s\" is known, but has no validate method.'",
",",
"$",
"key",
")",
")",
";",
"}",
"$",
"this",
"->",
"$",
"validate_method",
"(",
"$",
"value",
")",
";",
"}"
]
| Validates a value before it is being set.
@param string $key
@param mixed $value
@throws MiniContainerException | [
"Validates",
"a",
"value",
"before",
"it",
"is",
"being",
"set",
"."
]
| 09c70b421828624756e56591de41d5e86030f50e | https://github.com/donquixote/cellbrush/blob/09c70b421828624756e56591de41d5e86030f50e/src/MiniContainer/MiniContainerBase.php#L56-L70 | train |
donquixote/cellbrush | src/MiniContainer/MiniContainerBase.php | MiniContainerBase.valueForKey | protected function valueForKey($key) {
// Attempt to create the non-existing service.
$method = 'get_' . $key;
if (!method_exists($this, $method)) {
if (isset($this->defaults[$key])) {
return $this->defaults[$key];
}
// Keys are only 'known' if there is a get_ method.
throw new MiniContainerException(sprintf('Unknown key "%s".', $key));
}
return $this->$method();
} | php | protected function valueForKey($key) {
// Attempt to create the non-existing service.
$method = 'get_' . $key;
if (!method_exists($this, $method)) {
if (isset($this->defaults[$key])) {
return $this->defaults[$key];
}
// Keys are only 'known' if there is a get_ method.
throw new MiniContainerException(sprintf('Unknown key "%s".', $key));
}
return $this->$method();
} | [
"protected",
"function",
"valueForKey",
"(",
"$",
"key",
")",
"{",
"// Attempt to create the non-existing service.",
"$",
"method",
"=",
"'get_'",
".",
"$",
"key",
";",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"this",
",",
"$",
"method",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"defaults",
"[",
"$",
"key",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"defaults",
"[",
"$",
"key",
"]",
";",
"}",
"// Keys are only 'known' if there is a get_ method.",
"throw",
"new",
"MiniContainerException",
"(",
"sprintf",
"(",
"'Unknown key \"%s\".'",
",",
"$",
"key",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"$",
"method",
"(",
")",
";",
"}"
]
| Determines a value for the given key.
@param string $key
@return mixed | [
"Determines",
"a",
"value",
"for",
"the",
"given",
"key",
"."
]
| 09c70b421828624756e56591de41d5e86030f50e | https://github.com/donquixote/cellbrush/blob/09c70b421828624756e56591de41d5e86030f50e/src/MiniContainer/MiniContainerBase.php#L79-L90 | train |
donquixote/cellbrush | src/Columns/TableColumnsTrait.php | TableColumnsTrait.setColOrder | function setColOrder($orderedBaseColNames, $groupPrefix = null) {
$this->columns->setOrder($orderedBaseColNames, $groupPrefix);
return $this;
} | php | function setColOrder($orderedBaseColNames, $groupPrefix = null) {
$this->columns->setOrder($orderedBaseColNames, $groupPrefix);
return $this;
} | [
"function",
"setColOrder",
"(",
"$",
"orderedBaseColNames",
",",
"$",
"groupPrefix",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"columns",
"->",
"setOrder",
"(",
"$",
"orderedBaseColNames",
",",
"$",
"groupPrefix",
")",
";",
"return",
"$",
"this",
";",
"}"
]
| Sets the order for all columns or column groups at the top level, or at a
the relative top level within one group.
@param string[] $orderedBaseColNames
@param string|null $groupPrefix
@return $this
@throws \Exception | [
"Sets",
"the",
"order",
"for",
"all",
"columns",
"or",
"column",
"groups",
"at",
"the",
"top",
"level",
"or",
"at",
"a",
"the",
"relative",
"top",
"level",
"within",
"one",
"group",
"."
]
| 09c70b421828624756e56591de41d5e86030f50e | https://github.com/donquixote/cellbrush/blob/09c70b421828624756e56591de41d5e86030f50e/src/Columns/TableColumnsTrait.php#L65-L68 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.