repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
simpleapisecurity/php | src/Encryption.php | Encryption.decryptMessage | public static function decryptMessage($message, $key, $hashKey = '')
{
// Test the message and key for string validity.
Helpers::isString($message, 'Encryption', 'decryptMessage');
Helpers::isString($key, 'Encryption', 'decryptMessage');
Helpers::isString($hashKey, 'Encryption', 'decryptMessage');
// Create a special hashed key for encryption.
$key = Hash::hash($key, $hashKey, Constants::SECRETBOX_KEYBYTES);
// Validate and decode the paylload.
$payload = self::getJsonPayload($message);
$nonce = base64_decode($payload['nonce']);
$ciphertext = base64_decode($payload['ciphertext']);
// Open the secret box using the data provided.
$plaintext = \Sodium\crypto_secretbox_open($ciphertext, $nonce, $key);
// Test if the secret box returned usable data.
if ($plaintext === false) {
throw new Exceptions\DecryptionException("Failed to decrypt message using key.");
}
return unserialize($plaintext);
} | php | public static function decryptMessage($message, $key, $hashKey = '')
{
// Test the message and key for string validity.
Helpers::isString($message, 'Encryption', 'decryptMessage');
Helpers::isString($key, 'Encryption', 'decryptMessage');
Helpers::isString($hashKey, 'Encryption', 'decryptMessage');
// Create a special hashed key for encryption.
$key = Hash::hash($key, $hashKey, Constants::SECRETBOX_KEYBYTES);
// Validate and decode the paylload.
$payload = self::getJsonPayload($message);
$nonce = base64_decode($payload['nonce']);
$ciphertext = base64_decode($payload['ciphertext']);
// Open the secret box using the data provided.
$plaintext = \Sodium\crypto_secretbox_open($ciphertext, $nonce, $key);
// Test if the secret box returned usable data.
if ($plaintext === false) {
throw new Exceptions\DecryptionException("Failed to decrypt message using key.");
}
return unserialize($plaintext);
} | Returns the encrypted message in plaintext format.
@param string $message The encrypted message portion.
@param string $key The encryption key used with the message.
@param string $hashKey The key to hash the key with.
@return string The encrypted message in plaintext format.
@throws Exceptions\DecryptionException
@throws Exceptions\InvalidTypeException
@throws Exceptions\OutOfRangeException | https://github.com/simpleapisecurity/php/blob/e6cebf3213f4d7be54aa3a188d95a00113e3fda0/src/Encryption.php#L70-L89 |
simpleapisecurity/php | src/Encryption.php | Encryption.getJsonPayload | private static function getJsonPayload($payload)
{
$payload = json_decode(base64_decode($payload), true);
if (! $payload || self::isInvalidPayload($payload)) {
throw new Exceptions\DecryptionException('The payload is invalid.');
}
return $payload;
} | php | private static function getJsonPayload($payload)
{
$payload = json_decode(base64_decode($payload), true);
if (! $payload || self::isInvalidPayload($payload)) {
throw new Exceptions\DecryptionException('The payload is invalid.');
}
return $payload;
} | Get the JSON array from the given payload.
@param string $payload
@return array
@throws Exceptions\DecryptException | https://github.com/simpleapisecurity/php/blob/e6cebf3213f4d7be54aa3a188d95a00113e3fda0/src/Encryption.php#L99-L107 |
simpleapisecurity/php | src/Encryption.php | Encryption.signMessage | public static function signMessage($message, $key, $hashKey = '')
{
# Test the message and key for string validity.
Helpers::isString($message, 'Encryption', 'signMessage');
Helpers::isString($key, 'Encryption', 'signMessage');
Helpers::isString($hashKey, 'Encryption', 'signMessage');
# Create a special hashed key for encryption.
$key = Hash::hash($key, $hashKey, Constants::AUTH_KEYBYTES);
# Generate a MAC for the message.
$mac = \Sodium\crypto_auth($message, $key);
return base64_encode(json_encode([
'mac' => Helpers::bin2hex($mac),
'msg' => $message,
]));
} | php | public static function signMessage($message, $key, $hashKey = '')
{
# Test the message and key for string validity.
Helpers::isString($message, 'Encryption', 'signMessage');
Helpers::isString($key, 'Encryption', 'signMessage');
Helpers::isString($hashKey, 'Encryption', 'signMessage');
# Create a special hashed key for encryption.
$key = Hash::hash($key, $hashKey, Constants::AUTH_KEYBYTES);
# Generate a MAC for the message.
$mac = \Sodium\crypto_auth($message, $key);
return base64_encode(json_encode([
'mac' => Helpers::bin2hex($mac),
'msg' => $message,
]));
} | Returns a signed message to the client for authentication.
@param string $message The message to be signed.
@param string $key The signing key used with the message.
@param string $hashKey The key to hash the key with.
@return string A JSON string including the signing information and message.
@throws Exceptions\InvalidTypeException
@throws Exceptions\OutOfRangeException | https://github.com/simpleapisecurity/php/blob/e6cebf3213f4d7be54aa3a188d95a00113e3fda0/src/Encryption.php#L129-L146 |
simpleapisecurity/php | src/Encryption.php | Encryption.verifyMessage | public static function verifyMessage($message, $key, $hashKey = '')
{
# Test the message and key for string validity.
Helpers::isString($message, 'Encryption', 'verifyMessage');
Helpers::isString($key, 'Encryption', 'verifyMessage');
Helpers::isString($hashKey, 'Encryption', 'verifyMessage');
# Create a special hashed key for encryption.
$key = Hash::hash($key, $hashKey, Constants::AUTH_KEYBYTES);
# Decode the message from JSON.
$message = base64_decode(json_decode($message, true));
if (\Sodium\crypto_auth_verify(Helpers::hex2bin($message['mac']), $message['msg'], $key)) {
\Sodium\memzero($key);
return $message['msg'];
} else {
\Sodium\memzero($key);
throw new Exceptions\SignatureException('Signature for message invalid.');
}
} | php | public static function verifyMessage($message, $key, $hashKey = '')
{
# Test the message and key for string validity.
Helpers::isString($message, 'Encryption', 'verifyMessage');
Helpers::isString($key, 'Encryption', 'verifyMessage');
Helpers::isString($hashKey, 'Encryption', 'verifyMessage');
# Create a special hashed key for encryption.
$key = Hash::hash($key, $hashKey, Constants::AUTH_KEYBYTES);
# Decode the message from JSON.
$message = base64_decode(json_decode($message, true));
if (\Sodium\crypto_auth_verify(Helpers::hex2bin($message['mac']), $message['msg'], $key)) {
\Sodium\memzero($key);
return $message['msg'];
} else {
\Sodium\memzero($key);
throw new Exceptions\SignatureException('Signature for message invalid.');
}
} | Validates a message signature and returns the signed message.
@param string $message The signed message JSON string.
@param string $key The signing key used with the message.
@param string $hashKey The key to hash the key with.
@return string A string returning the output of the signed message.
@throws Exceptions\InvalidTypeException
@throws Exceptions\SignatureException | https://github.com/simpleapisecurity/php/blob/e6cebf3213f4d7be54aa3a188d95a00113e3fda0/src/Encryption.php#L158-L179 |
simpleapisecurity/php | src/Encryption.php | Encryption.encryptSignMessage | public static function encryptSignMessage($message, $encryptionKey, $signatureKey, $hashKey = '')
{
# Test the message and key for string validity.
Helpers::isString($message, 'Encryption', 'encryptSignMessage');
Helpers::isString($encryptionKey, 'Encryption', 'encryptSignMessage');
Helpers::isString($signatureKey, 'Encryption', 'encryptSignMessage');
Helpers::isString($hashKey, 'Encryption', 'encryptSignMessage');
$message = self::encryptMessage($message, $encryptionKey, $hashKey);
return self::signMessage($message, $signatureKey, $hashKey);
} | php | public static function encryptSignMessage($message, $encryptionKey, $signatureKey, $hashKey = '')
{
# Test the message and key for string validity.
Helpers::isString($message, 'Encryption', 'encryptSignMessage');
Helpers::isString($encryptionKey, 'Encryption', 'encryptSignMessage');
Helpers::isString($signatureKey, 'Encryption', 'encryptSignMessage');
Helpers::isString($hashKey, 'Encryption', 'encryptSignMessage');
$message = self::encryptMessage($message, $encryptionKey, $hashKey);
return self::signMessage($message, $signatureKey, $hashKey);
} | Sign and encrypt a message for security.
@param string $message The message to be encrypted and signed for transport.
@param string $encryptionKey The encryption key used with the message.
@param string $signatureKey The signing key used with the message.
@param string $hashKey The key to hash the key with.
@return string The encrypted and signed JSON string with message data.
@throws Exceptions\InvalidTypeException | https://github.com/simpleapisecurity/php/blob/e6cebf3213f4d7be54aa3a188d95a00113e3fda0/src/Encryption.php#L191-L202 |
simpleapisecurity/php | src/Encryption.php | Encryption.decryptVerifyMessage | public static function decryptVerifyMessage($message, $encryptionKey, $signatureKey, $hashKey = '')
{
# Test the message and key for string validity.
Helpers::isString($message, 'Encryption', 'decryptVerifyMessage');
Helpers::isString($encryptionKey, 'Encryption', 'decryptVerifyMessage');
Helpers::isString($signatureKey, 'Encryption', 'decryptVerifyMessage');
Helpers::isString($hashKey, 'Encryption', 'decryptVerifyMessage');
$message = self::verifyMessage($message, $signatureKey, $hashKey);
return self::decryptMessage($message, $encryptionKey, $hashKey);
} | php | public static function decryptVerifyMessage($message, $encryptionKey, $signatureKey, $hashKey = '')
{
# Test the message and key for string validity.
Helpers::isString($message, 'Encryption', 'decryptVerifyMessage');
Helpers::isString($encryptionKey, 'Encryption', 'decryptVerifyMessage');
Helpers::isString($signatureKey, 'Encryption', 'decryptVerifyMessage');
Helpers::isString($hashKey, 'Encryption', 'decryptVerifyMessage');
$message = self::verifyMessage($message, $signatureKey, $hashKey);
return self::decryptMessage($message, $encryptionKey, $hashKey);
} | Verify and decrypt a message for security.
@param string $message The message to be encrypted and signed for transport.
@param string $encryptionKey The encryption key used with the message.
@param string $signatureKey The signing key used with the message.
@param string $hashKey The key to hash the key with.
@return string The string of the signed and decrypted message.
@throws Exceptions\InvalidTypeException
@throws Exceptions\SignatureException | https://github.com/simpleapisecurity/php/blob/e6cebf3213f4d7be54aa3a188d95a00113e3fda0/src/Encryption.php#L215-L226 |
anklimsk/cakephp-console-installer | View/Helper/CheckResultHelper.php | CheckResultHelper.getStateElement | public function getStateElement($state = null) {
if (is_bool($state) && ($state === true)) {
$state = 2;
}
switch ((int)$state) {
case 2:
$stateText = $this->Html->tag('span', '', ['class' => 'fas fa-check']);
$titleText = __d('cake_installer', 'Ok');
$labelClass = 'label-success';
break;
case 1:
$stateText = $this->Html->tag('span', '', ['class' => 'fas fa-minus']);
$titleText = __d('cake_installer', 'Ok');
$labelClass = 'label-warning';
break;
default:
$stateText = $this->Html->tag('span', '', ['class' => 'fas fa-times']);
$titleText = __d('cake_installer', 'Bad');
$labelClass = 'label-danger';
}
return $this->Html->tag('span', $stateText, [
'class' => 'label' . ' ' . $labelClass,
'title' => $titleText, 'data-toggle' => 'tooltip']);
} | php | public function getStateElement($state = null) {
if (is_bool($state) && ($state === true)) {
$state = 2;
}
switch ((int)$state) {
case 2:
$stateText = $this->Html->tag('span', '', ['class' => 'fas fa-check']);
$titleText = __d('cake_installer', 'Ok');
$labelClass = 'label-success';
break;
case 1:
$stateText = $this->Html->tag('span', '', ['class' => 'fas fa-minus']);
$titleText = __d('cake_installer', 'Ok');
$labelClass = 'label-warning';
break;
default:
$stateText = $this->Html->tag('span', '', ['class' => 'fas fa-times']);
$titleText = __d('cake_installer', 'Bad');
$labelClass = 'label-danger';
}
return $this->Html->tag('span', $stateText, [
'class' => 'label' . ' ' . $labelClass,
'title' => $titleText, 'data-toggle' => 'tooltip']);
} | Build HTML element with status icon from status value
@param int $state State for build HTML elemeth.
Integer value:
- `0` - Bad;
- `1` - Warning;
- `2` - Success.
@return string Result HTML element with status text | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/View/Helper/CheckResultHelper.php#L38-L63 |
anklimsk/cakephp-console-installer | View/Helper/CheckResultHelper.php | CheckResultHelper.getStateItemClass | public function getStateItemClass($state = null) {
if (is_bool($state) && ($state === true)) {
$state = 2;
}
switch ((int)$state) {
case 2:
$classItem = '';
break;
case 1:
$classItem = 'list-group-item-warning';
break;
default:
$classItem = 'list-group-item-danger';
}
return $classItem;
} | php | public function getStateItemClass($state = null) {
if (is_bool($state) && ($state === true)) {
$state = 2;
}
switch ((int)$state) {
case 2:
$classItem = '';
break;
case 1:
$classItem = 'list-group-item-warning';
break;
default:
$classItem = 'list-group-item-danger';
}
return $classItem;
} | Return class for list element from status value
@param int $state State for build HTML elemeth.
Integer value:
- `0` - Bad;
- `1` - Warning;
- `2` - Success.
@return string Return class name | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/View/Helper/CheckResultHelper.php#L75-L92 |
anklimsk/cakephp-console-installer | View/Helper/CheckResultHelper.php | CheckResultHelper.getStateList | public function getStateList($list = null) {
$result = '';
if (empty($list)) {
return $result;
}
$listText = '';
foreach ($list as $listItem) {
$classItem = '';
if (is_array($listItem)) {
if (!isset($listItem['textItem'])) {
continue;
}
$textItem = $listItem['textItem'];
if (isset($listItem['classItem']) && !empty($listItem['classItem'])) {
$classItem = ' ' . $listItem['classItem'];
}
} else {
$textItem = $listItem;
}
$listText .= $this->Html->tag('li', $textItem, ['class' => 'list-group-item' . $classItem]);
}
if (empty($listText)) {
return $result;
}
$result = $this->Html->tag('ul', $listText, ['class' => 'list-group']);
return $result;
} | php | public function getStateList($list = null) {
$result = '';
if (empty($list)) {
return $result;
}
$listText = '';
foreach ($list as $listItem) {
$classItem = '';
if (is_array($listItem)) {
if (!isset($listItem['textItem'])) {
continue;
}
$textItem = $listItem['textItem'];
if (isset($listItem['classItem']) && !empty($listItem['classItem'])) {
$classItem = ' ' . $listItem['classItem'];
}
} else {
$textItem = $listItem;
}
$listText .= $this->Html->tag('li', $textItem, ['class' => 'list-group-item' . $classItem]);
}
if (empty($listText)) {
return $result;
}
$result = $this->Html->tag('ul', $listText, ['class' => 'list-group']);
return $result;
} | Return list of states
@param array $list List of states for rendering in format:
- key `textItem`, value - text of list item;
- key `classItem`, value - class of list item.
@return string Return list of states | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/View/Helper/CheckResultHelper.php#L102-L133 |
brainexe/core | src/DependencyInjection/CompilerPass/SetDefinitionFileCompilerPass.php | SetDefinitionFileCompilerPass.process | public function process(ContainerBuilder $container)
{
foreach ($container->getDefinitions() as $serviceId => $definition) {
try {
$reflection = new ReflectionClass($definition->getClass());
} catch (ReflectionException $e) {
continue;
}
$filename = $reflection->getFileName();
if (!empty($filename)) {
$definition->setFile($filename);
}
}
} | php | public function process(ContainerBuilder $container)
{
foreach ($container->getDefinitions() as $serviceId => $definition) {
try {
$reflection = new ReflectionClass($definition->getClass());
} catch (ReflectionException $e) {
continue;
}
$filename = $reflection->getFileName();
if (!empty($filename)) {
$definition->setFile($filename);
}
}
} | {@inheritdoc} | https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/DependencyInjection/CompilerPass/SetDefinitionFileCompilerPass.php#L20-L34 |
fxpio/fxp-gluon | Twig/Extension/PropertyPathExtension.php | PropertyPathExtension.propertyPath | public function propertyPath($data, $propertyPath)
{
if (null !== $propertyPath && !$propertyPath instanceof PropertyPathInterface) {
$propertyPath = new PropertyPath($propertyPath);
}
if ($propertyPath instanceof PropertyPathInterface && (\is_object($data) || $data instanceof \ArrayAccess)) {
$data = $this->propertyAccessor->getValue($data, $propertyPath);
}
return $data;
} | php | public function propertyPath($data, $propertyPath)
{
if (null !== $propertyPath && !$propertyPath instanceof PropertyPathInterface) {
$propertyPath = new PropertyPath($propertyPath);
}
if ($propertyPath instanceof PropertyPathInterface && (\is_object($data) || $data instanceof \ArrayAccess)) {
$data = $this->propertyAccessor->getValue($data, $propertyPath);
}
return $data;
} | Get the data defined by property path.
@param mixed $data The data
@param PropertyPathInterface|string|null $propertyPath The property path
@return mixed | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Twig/Extension/PropertyPathExtension.php#L59-L70 |
pmdevelopment/tool-bundle | Components/Helper/FileUtilityHelper.php | FileUtilityHelper.getIconByExtension | public static function getIconByExtension($extension)
{
if ('pdf' === $extension) {
return 'file-pdf-o';
}
if (true === in_array($extension, self::extensionsArchive())) {
return 'file-archive-o';
}
if (true === in_array($extension, self::extensionsImage())) {
return 'file-image-o';
}
if (true === in_array($extension, self::extensionsCode())) {
return 'file-code-o';
}
if (true === in_array($extension, self::extensionsVideo())) {
return 'file-video-o';
}
if (true === in_array($extension, self::extensionsAudio())) {
return 'file-audio-o';
}
if (true === in_array($extension, self::extensionsExcel())) {
return 'file-excel-o';
}
if (true === in_array($extension, self::extensionsPowerPoint())) {
return 'file-powerpoint-o';
}
if (true === in_array($extension, self::extensionsWord())) {
return 'file-word-o';
}
return null;
} | php | public static function getIconByExtension($extension)
{
if ('pdf' === $extension) {
return 'file-pdf-o';
}
if (true === in_array($extension, self::extensionsArchive())) {
return 'file-archive-o';
}
if (true === in_array($extension, self::extensionsImage())) {
return 'file-image-o';
}
if (true === in_array($extension, self::extensionsCode())) {
return 'file-code-o';
}
if (true === in_array($extension, self::extensionsVideo())) {
return 'file-video-o';
}
if (true === in_array($extension, self::extensionsAudio())) {
return 'file-audio-o';
}
if (true === in_array($extension, self::extensionsExcel())) {
return 'file-excel-o';
}
if (true === in_array($extension, self::extensionsPowerPoint())) {
return 'file-powerpoint-o';
}
if (true === in_array($extension, self::extensionsWord())) {
return 'file-word-o';
}
return null;
} | Get FontAwesome Icon By Extension
@param string $extension
@return null|string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Components/Helper/FileUtilityHelper.php#L147-L186 |
Vyki/mva-dbm | src/Mva/Dbm/Connection.php | Connection.connect | public function connect()
{
if ($this->connected) {
return;
}
$this->driver->connect($this->config);
$this->connected = TRUE;
} | php | public function connect()
{
if ($this->connected) {
return;
}
$this->driver->connect($this->config);
$this->connected = TRUE;
} | Connects to a database
@return void
@throws ConnectionException | https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Connection.php#L52-L60 |
Vyki/mva-dbm | src/Mva/Dbm/Connection.php | Connection.getQuery | public function getQuery()
{
if (!$this->query) {
$this->query = new Query($this->driver, $this->preprocessor);
}
return $this->query;
} | php | public function getQuery()
{
if (!$this->query) {
$this->query = new Query($this->driver, $this->preprocessor);
}
return $this->query;
} | Returns parameter builder
@return Query | https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Connection.php#L84-L91 |
Vyki/mva-dbm | src/Mva/Dbm/Connection.php | Connection.createDriver | private function createDriver(array $config)
{
if (empty($config['driver'])) {
throw new InvalidStateException('Undefined driver');
} elseif ($config['driver'] instanceof IDriver) {
return $config['driver'];
} else {
$name = ucfirst($config['driver']);
$class = "Mva\\Dbm\\Driver\\{$name}\\{$name}Driver";
return new $class;
}
} | php | private function createDriver(array $config)
{
if (empty($config['driver'])) {
throw new InvalidStateException('Undefined driver');
} elseif ($config['driver'] instanceof IDriver) {
return $config['driver'];
} else {
$name = ucfirst($config['driver']);
$class = "Mva\\Dbm\\Driver\\{$name}\\{$name}Driver";
return new $class;
}
} | Creates a IDriver instance.
@param array $config
@return Driver\IDriver | https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Connection.php#L126-L137 |
luoxiaojun1992/lb_framework | components/request/BaseRequest.php | BaseRequest.validate | public function validate($rules = [], $errors = [])
{
foreach ($rules as $param => $subRules) {
$paramValue = $this->getParam($param);
foreach ($subRules as $key => $rule) {
$isError = false;
if (!is_array($rule)) {
switch ($rule) {
case self::VALIDATE_REQUIRED:
if (is_null($paramValue)) {
$isError = true;
}
break;
case self::VALIDATE_MOBILE:
if (!ValidationHelper::isMobile($paramValue)) {
$isError = true;
}
break;
}
} else {
switch ($key) {
case self::VALIDATE_ENUM:
if (!in_array($paramValue, $rule)) {
$isError = true;
}
break;
}
}
if ($isError) {
$errCode = self::ERROR_INVALID_PARAM;
$errMsg = self::errorMsg[self::ERROR_INVALID_PARAM];
if (is_array($rule)) {
$rule = $key;
}
if (isset($errors[$param][$rule]['code'])) {
$errCode = $errors[$param][$rule]['code'];
}
if (isset($errors[$param][$rule]['msg'])) {
$errMsg = str_replace('{param}', $param, $errors[$param][$rule]['msg']);
}
throw new ParamException($errMsg, $errCode);
}
}
}
} | php | public function validate($rules = [], $errors = [])
{
foreach ($rules as $param => $subRules) {
$paramValue = $this->getParam($param);
foreach ($subRules as $key => $rule) {
$isError = false;
if (!is_array($rule)) {
switch ($rule) {
case self::VALIDATE_REQUIRED:
if (is_null($paramValue)) {
$isError = true;
}
break;
case self::VALIDATE_MOBILE:
if (!ValidationHelper::isMobile($paramValue)) {
$isError = true;
}
break;
}
} else {
switch ($key) {
case self::VALIDATE_ENUM:
if (!in_array($paramValue, $rule)) {
$isError = true;
}
break;
}
}
if ($isError) {
$errCode = self::ERROR_INVALID_PARAM;
$errMsg = self::errorMsg[self::ERROR_INVALID_PARAM];
if (is_array($rule)) {
$rule = $key;
}
if (isset($errors[$param][$rule]['code'])) {
$errCode = $errors[$param][$rule]['code'];
}
if (isset($errors[$param][$rule]['msg'])) {
$errMsg = str_replace('{param}', $param, $errors[$param][$rule]['msg']);
}
throw new ParamException($errMsg, $errCode);
}
}
}
} | 校验参数
@param array $rules
@param array $errors
@throws ParamException | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/request/BaseRequest.php#L38-L82 |
SpoonX/SxBootstrap | src/SxBootstrap/View/Helper/Bootstrap/Pager.php | Pager.render | public function render()
{
$paginationData = $this->paginator->getPages();
$previous = $this->getElement()->spawnChild('li');
$next = $this->getElement()->spawnChild('li');
$previousAnchor = $previous->spawnChild('a')->setContent($this->getPrevLabel());
$nextAnchor = $next->spawnChild('a')->setContent($this->getNextLabel());
$this->getElement()->addAttributes($this->getListAttributes());
$previousAnchor->setAttributes($this->getPreviousAttributes());
$nextAnchor->setAttributes($this->getNextAttributes());
if (empty($paginationData->previous)) {
$previous->addClass('disabled');
} else {
$previousAnchor->addAttribute('data-page', $paginationData->previous);
$previousAnchor->addAttribute('href', $this->getUrl(
$this->getRoute(),
array_merge(
array('page' => $paginationData->previous),
$this->getRouteParams()
)
));
}
if (empty($paginationData->next)) {
$next->addClass('disabled');
} else {
$nextAnchor->addAttribute('data-page', $paginationData->next);
$nextAnchor->addAttribute('href', $this->getUrl(
$this->getRoute(),
array_merge(
array('page' => $paginationData->next),
$this->getRouteParams()
)
));
}
if ($this->align) {
$previous->addClass('previous');
$next->addClass('next');
}
return $this->getElement()->render();
} | php | public function render()
{
$paginationData = $this->paginator->getPages();
$previous = $this->getElement()->spawnChild('li');
$next = $this->getElement()->spawnChild('li');
$previousAnchor = $previous->spawnChild('a')->setContent($this->getPrevLabel());
$nextAnchor = $next->spawnChild('a')->setContent($this->getNextLabel());
$this->getElement()->addAttributes($this->getListAttributes());
$previousAnchor->setAttributes($this->getPreviousAttributes());
$nextAnchor->setAttributes($this->getNextAttributes());
if (empty($paginationData->previous)) {
$previous->addClass('disabled');
} else {
$previousAnchor->addAttribute('data-page', $paginationData->previous);
$previousAnchor->addAttribute('href', $this->getUrl(
$this->getRoute(),
array_merge(
array('page' => $paginationData->previous),
$this->getRouteParams()
)
));
}
if (empty($paginationData->next)) {
$next->addClass('disabled');
} else {
$nextAnchor->addAttribute('data-page', $paginationData->next);
$nextAnchor->addAttribute('href', $this->getUrl(
$this->getRoute(),
array_merge(
array('page' => $paginationData->next),
$this->getRouteParams()
)
));
}
if ($this->align) {
$previous->addClass('previous');
$next->addClass('next');
}
return $this->getElement()->render();
} | Return the HTML string of this HTML element
@return string | https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Pager.php#L140-L185 |
SpoonX/SxBootstrap | src/SxBootstrap/View/Helper/Bootstrap/Pager.php | Pager.translateLabel | protected function translateLabel($label)
{
if (null !== ($translator = $this->getTranslator())) {
$label = $translator->translate(
$label, $this->getTranslatorTextDomain()
);
}
return $label;
} | php | protected function translateLabel($label)
{
if (null !== ($translator = $this->getTranslator())) {
$label = $translator->translate(
$label, $this->getTranslatorTextDomain()
);
}
return $label;
} | @param $label
@return string | https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Pager.php#L289-L298 |
MetaModels/attribute_translatedurl | src/Helper/UpgradeHandler.php | UpgradeHandler.ensureIndexNameAttIdLanguage | private function ensureIndexNameAttIdLanguage()
{
if (!($this->database->tableExists('tl_metamodel_translatedurl'))) {
return;
}
// Renamed in 2.0.0-alpha2 (due to database.sql => dca movement).
if (!$this->database->indexExists('att_lang', 'tl_metamodel_translatedurl', true)) {
return;
}
$this->database->execute(
'ALTER TABLE `tl_metamodel_translatedurl` DROP INDEX `att_lang`;'
);
$this->database->execute(
'ALTER TABLE `tl_metamodel_translatedurl` ADD KEY `att_id_language` (`att_id`, `language`);'
);
} | php | private function ensureIndexNameAttIdLanguage()
{
if (!($this->database->tableExists('tl_metamodel_translatedurl'))) {
return;
}
// Renamed in 2.0.0-alpha2 (due to database.sql => dca movement).
if (!$this->database->indexExists('att_lang', 'tl_metamodel_translatedurl', true)) {
return;
}
$this->database->execute(
'ALTER TABLE `tl_metamodel_translatedurl` DROP INDEX `att_lang`;'
);
$this->database->execute(
'ALTER TABLE `tl_metamodel_translatedurl` ADD KEY `att_id_language` (`att_id`, `language`);'
);
} | Ensure that the index types are correct.
@return void | https://github.com/MetaModels/attribute_translatedurl/blob/ad6b4967244614be49d382934043c766b5fa08d8/src/Helper/UpgradeHandler.php#L65-L81 |
MetaModels/attribute_translatedurl | src/Helper/UpgradeHandler.php | UpgradeHandler.ensureHrefDefaultsToNull | private function ensureHrefDefaultsToNull()
{
if (!($this->database->tableExists('tl_metamodel_translatedurl'))) {
return;
}
foreach ($this->database->listFields('tl_metamodel_translatedurl', true) as $field) {
if ('href' == $field['name'] && $field['type'] != 'index') {
// Already updated?
if ('NOT NULL' === $field['null']) {
$this->database->execute(
'ALTER TABLE `tl_metamodel_translatedurl` CHANGE `href` `href` varchar(255) NULL;'
);
return;
}
// Found!
break;
}
}
} | php | private function ensureHrefDefaultsToNull()
{
if (!($this->database->tableExists('tl_metamodel_translatedurl'))) {
return;
}
foreach ($this->database->listFields('tl_metamodel_translatedurl', true) as $field) {
if ('href' == $field['name'] && $field['type'] != 'index') {
// Already updated?
if ('NOT NULL' === $field['null']) {
$this->database->execute(
'ALTER TABLE `tl_metamodel_translatedurl` CHANGE `href` `href` varchar(255) NULL;'
);
return;
}
// Found!
break;
}
}
} | Ensure the default value for the href column is correct.
@return void | https://github.com/MetaModels/attribute_translatedurl/blob/ad6b4967244614be49d382934043c766b5fa08d8/src/Helper/UpgradeHandler.php#L88-L107 |
salernolabs/camelize | src/Uncamel.php | Uncamel.uncamelize | public function uncamelize($input)
{
$input = trim($input);
if (empty($input))
{
throw new \Exception("Can not uncamelize an empty string.");
}
$output = '';
for ($i = 0; $i < mb_strlen($input); ++$i)
{
$character = mb_substr($input, $i, 1);
$isCapital = ($character == mb_strtoupper($character));
if ($isCapital)
{
//We don't want to add the replacement character if its the first one in the list so we don't prepend
if ($i != 0)
{
$output .= $this->replacementCharacter;
}
if ($this->shouldCapitalizeFirstLetter)
{
$output .= $character;
}
else
{
$output .= mb_strtolower($character);
}
}
else
{
if ($i == 0 && $this->shouldCapitalizeFirstLetter)
{
$output .= mb_strtoupper($character);
}
else
{
$output .= $character;
}
}
}
return $output;
} | php | public function uncamelize($input)
{
$input = trim($input);
if (empty($input))
{
throw new \Exception("Can not uncamelize an empty string.");
}
$output = '';
for ($i = 0; $i < mb_strlen($input); ++$i)
{
$character = mb_substr($input, $i, 1);
$isCapital = ($character == mb_strtoupper($character));
if ($isCapital)
{
//We don't want to add the replacement character if its the first one in the list so we don't prepend
if ($i != 0)
{
$output .= $this->replacementCharacter;
}
if ($this->shouldCapitalizeFirstLetter)
{
$output .= $character;
}
else
{
$output .= mb_strtolower($character);
}
}
else
{
if ($i == 0 && $this->shouldCapitalizeFirstLetter)
{
$output .= mb_strtoupper($character);
}
else
{
$output .= $character;
}
}
}
return $output;
} | Uncamelize a string
@param $input
@return string | https://github.com/salernolabs/camelize/blob/6098e9827fd21509592fc7062b653582d0dd00d1/src/Uncamel.php#L55-L103 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/DisplayBlock/Strategies/AudienceAnalysisStrategy.php | AudienceAnalysisStrategy.show | public function show(ReadBlockInterface $block)
{
return $this->render(
'OpenOrchestraDisplayBundle:Block/AudienceAnalysis:' . $block->getAttribute('tag_type') . '.html.twig',
array(
'attributes' => $block->getAttributes(),
'page' => $this->requestStack->getCurrentRequest()->attributes->get('nodeId')
)
);
} | php | public function show(ReadBlockInterface $block)
{
return $this->render(
'OpenOrchestraDisplayBundle:Block/AudienceAnalysis:' . $block->getAttribute('tag_type') . '.html.twig',
array(
'attributes' => $block->getAttributes(),
'page' => $this->requestStack->getCurrentRequest()->attributes->get('nodeId')
)
);
} | Perform the show action for a block
@param ReadBlockInterface $block
@return Response | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/DisplayBlock/Strategies/AudienceAnalysisStrategy.php#L57-L66 |
phpcq/autoload-validation | src/AutoloadValidator/FilesValidator.php | FilesValidator.getLoader | public function getLoader()
{
$this->validate();
$previous = spl_autoload_functions();
foreach ($this->information as $path) {
if ($path = realpath($this->prependPathWithBaseDir($path))) {
require $path;
}
}
$found = array();
$after = spl_autoload_functions();
foreach ($after as $loader) {
if (!in_array($loader, $previous)) {
spl_autoload_unregister($loader);
$found[] = $loader;
}
}
return function ($class) use ($found) {
foreach ($found as $loader) {
if (call_user_func($loader, $class)) {
return true;
}
}
return null;
};
} | php | public function getLoader()
{
$this->validate();
$previous = spl_autoload_functions();
foreach ($this->information as $path) {
if ($path = realpath($this->prependPathWithBaseDir($path))) {
require $path;
}
}
$found = array();
$after = spl_autoload_functions();
foreach ($after as $loader) {
if (!in_array($loader, $previous)) {
spl_autoload_unregister($loader);
$found[] = $loader;
}
}
return function ($class) use ($found) {
foreach ($found as $loader) {
if (call_user_func($loader, $class)) {
return true;
}
}
return null;
};
} | {@inheritDoc} | https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/AutoloadValidator/FilesValidator.php#L33-L63 |
phpcq/autoload-validation | src/AutoloadValidator/FilesValidator.php | FilesValidator.doValidate | protected function doValidate()
{
// Scan all directories mentioned and validate the class map against the entries.
foreach ($this->information as $path) {
$subPath = $this->prependPathWithBaseDir($path);
if (!realpath($subPath)) {
$this->report->error(new FileNotFoundViolation($this->getName(), $path));
}
}
} | php | protected function doValidate()
{
// Scan all directories mentioned and validate the class map against the entries.
foreach ($this->information as $path) {
$subPath = $this->prependPathWithBaseDir($path);
if (!realpath($subPath)) {
$this->report->error(new FileNotFoundViolation($this->getName(), $path));
}
}
} | {@inheritDoc} | https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/AutoloadValidator/FilesValidator.php#L68-L77 |
zircote/Uuid | library/Uuid/Uuid.php | Uuid.setUuid | public function setUuid($chars = null){
if (null === $chars && 32 != strlen($chars)) {
$chars = md5 ( uniqid ( mt_rand (), true ) );
} elseif ($chars !== null && 32 !== strlen($chars)){
throw new \UnexpectedValueException('invalid characters for UUID generation provided');
}
$this->uuid =
substr ( $chars, 0, 8 ) . '-' .
substr ( $chars, 8, 4 ) . '-' .
substr ( $chars, 12, 4 ) . '-' .
substr ( $chars, 16, 4 ) . '-' .
substr ( $chars, 20, 12 ) ;
return $this;
} | php | public function setUuid($chars = null){
if (null === $chars && 32 != strlen($chars)) {
$chars = md5 ( uniqid ( mt_rand (), true ) );
} elseif ($chars !== null && 32 !== strlen($chars)){
throw new \UnexpectedValueException('invalid characters for UUID generation provided');
}
$this->uuid =
substr ( $chars, 0, 8 ) . '-' .
substr ( $chars, 8, 4 ) . '-' .
substr ( $chars, 12, 4 ) . '-' .
substr ( $chars, 16, 4 ) . '-' .
substr ( $chars, 20, 12 ) ;
return $this;
} | @param null|string $chars
@return Uuid
@throws \UnexpectedValueException | https://github.com/zircote/Uuid/blob/98129bd633bbd7396dbd3263ba9633ba815553ba/library/Uuid/Uuid.php#L47-L60 |
morrislaptop/error-tracker-adapter | src/Adapter/Rollbar.php | Rollbar.report | public function report(Exception $e, array $extra = [])
{
if ($extra) {
throw new \InvalidArgumentException('Rollbar doesn\'t support context for exceptions');
}
$this->rollbar->report_exception($e);
} | php | public function report(Exception $e, array $extra = [])
{
if ($extra) {
throw new \InvalidArgumentException('Rollbar doesn\'t support context for exceptions');
}
$this->rollbar->report_exception($e);
} | Reports the exception to the SaaS platform
@param Exception $e
@param array $extra
@return mixed | https://github.com/morrislaptop/error-tracker-adapter/blob/955aea67c45892da2b8813517600f338bada6a01/src/Adapter/Rollbar.php#L28-L35 |
xelax90/xelax-admin | src/XelaxAdmin/Provider/ListController.php | ListController.getRules | public function getRules(){
if ($this->rules !== null) {
return $this->rules;
}
$options = $this->getServiceLocator()->get('XelaxAdmin\ListControllerOptions');
$rules = array();
foreach ($options as $name => $option){
/* @var $option Options\ListControllerOptions */
// get XelaxAdmin route name
if(!empty($option->getRouteBase())){
$route = $option->getRouteBase();
} else {
$route = $name;
}
$rules = array_merge($rules, $this->getRulesController($route, $name, $option)['allow']);
}
$this->rules = array('allow' => $rules);
return $this->rules;
} | php | public function getRules(){
if ($this->rules !== null) {
return $this->rules;
}
$options = $this->getServiceLocator()->get('XelaxAdmin\ListControllerOptions');
$rules = array();
foreach ($options as $name => $option){
/* @var $option Options\ListControllerOptions */
// get XelaxAdmin route name
if(!empty($option->getRouteBase())){
$route = $option->getRouteBase();
} else {
$route = $name;
}
$rules = array_merge($rules, $this->getRulesController($route, $name, $option)['allow']);
}
$this->rules = array('allow' => $rules);
return $this->rules;
} | {@inheritDoc} | https://github.com/xelax90/xelax-admin/blob/eb8133384b74e18f6641689f290c6ba956641b6d/src/XelaxAdmin/Provider/ListController.php#L65-L85 |
xervice/core | src/Xervice/Core/Business/Model/Locator/Locator.php | Locator.getServiceProxy | protected function getServiceProxy(string $service): LocatorProxyInterface
{
return new LocatorProxy(
$this->coreNamespaces,
$this->projectNamespaces,
ucfirst($service)
);
} | php | protected function getServiceProxy(string $service): LocatorProxyInterface
{
return new LocatorProxy(
$this->coreNamespaces,
$this->projectNamespaces,
ucfirst($service)
);
} | @param string $service
@return \Xervice\Core\Business\Model\Locator\Proxy\AbstractLocatorProxy | https://github.com/xervice/core/blob/f2005706e1363a62bf929fc84b2b45aaedf94f16/src/Xervice/Core/Business/Model/Locator/Locator.php#L82-L89 |
pmdevelopment/tool-bundle | Services/CronjobService.php | CronjobService.getListeners | public function getListeners($resultType = self::FULL_RESULT)
{
$listeners = [];
foreach ($this->getEventDispatcher()->getListeners(CronEvent::NAME) as $listener) {
$listenerClass = get_class($listener[0]);
if (!$listener[0] instanceof CronEventListenerInterface) {
$this->getLogger()->addError(sprintf('%s without %s', $listenerClass, CronEventListenerInterface::class));
continue;
}
if (self::FLAT_RESULT === $resultType) {
$listeners[] = $listenerClass;
continue;
}
$type = $listener[0]::getRepeatedType();
if (false === isset($listeners[$type])) {
$listeners[$type] = [];
}
$listeners[$type][] = $listenerClass;
}
return $listeners;
} | php | public function getListeners($resultType = self::FULL_RESULT)
{
$listeners = [];
foreach ($this->getEventDispatcher()->getListeners(CronEvent::NAME) as $listener) {
$listenerClass = get_class($listener[0]);
if (!$listener[0] instanceof CronEventListenerInterface) {
$this->getLogger()->addError(sprintf('%s without %s', $listenerClass, CronEventListenerInterface::class));
continue;
}
if (self::FLAT_RESULT === $resultType) {
$listeners[] = $listenerClass;
continue;
}
$type = $listener[0]::getRepeatedType();
if (false === isset($listeners[$type])) {
$listeners[$type] = [];
}
$listeners[$type][] = $listenerClass;
}
return $listeners;
} | Get Listeners
@param bool $resultType
@return array | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Services/CronjobService.php#L37-L65 |
phPoirot/ApiClient | AccessTokenObject.php | AccessTokenObject.getDateTimeExpiration | function getDateTimeExpiration()
{
if (! $this->datetimeExpiration ) {
if ($this->expiresIn) {
// Maybe not include this field
$exprDateTime = __( new \DateTime() )
->add( new \DateInterval(sprintf('PT%sS', $this->expiresIn)) );
$this->datetimeExpiration = $exprDateTime;
}
}
return $this->datetimeExpiration;
} | php | function getDateTimeExpiration()
{
if (! $this->datetimeExpiration ) {
if ($this->expiresIn) {
// Maybe not include this field
$exprDateTime = __( new \DateTime() )
->add( new \DateInterval(sprintf('PT%sS', $this->expiresIn)) );
$this->datetimeExpiration = $exprDateTime;
}
}
return $this->datetimeExpiration;
} | //TODO Datetime instead of DateTime
Get the token's expiry date time
@return \DateTime | https://github.com/phPoirot/ApiClient/blob/4753197be9f961ab1d915371a87757dbd8efcf9a/AccessTokenObject.php#L75-L90 |
phPoirot/ApiClient | AccessTokenObject.php | AccessTokenObject.setExpiresIn | function setExpiresIn($expiry)
{
$this->expiresIn = $expiry;
$this->datetimeExpiration = $this->getDateTimeExpiration();
return $this;
} | php | function setExpiresIn($expiry)
{
$this->expiresIn = $expiry;
$this->datetimeExpiration = $this->getDateTimeExpiration();
return $this;
} | Set Expiry DateTime
@param \DateTime $expiry
@return $this | https://github.com/phPoirot/ApiClient/blob/4753197be9f961ab1d915371a87757dbd8efcf9a/AccessTokenObject.php#L112-L117 |
stackpr/quipxml | src/Contact/QuipContact.php | QuipContact.loadEmpty | static public function loadEmpty($defaults = NULL) {
$defaults = array_merge(array(
'FN' => '',
), (array) $defaults);
$ical = implode("\n", array(
'BEGIN:VCARD',
'VERSION:3.0',
'PRODID:QuipContact',
'N:',
'FN:' . QuipContactVcfFormatter::escape($defaults['FN']),
'END:VCARD',
));
return self::loadVcard($ical);
} | php | static public function loadEmpty($defaults = NULL) {
$defaults = array_merge(array(
'FN' => '',
), (array) $defaults);
$ical = implode("\n", array(
'BEGIN:VCARD',
'VERSION:3.0',
'PRODID:QuipContact',
'N:',
'FN:' . QuipContactVcfFormatter::escape($defaults['FN']),
'END:VCARD',
));
return self::loadVcard($ical);
} | Initialize an empty contact.
@param array $defaults
@return \QuipXml\Xml\QuipXmlElement | https://github.com/stackpr/quipxml/blob/472e0d98a90aa0a283aac933158d830311480ff8/src/Contact/QuipContact.php#L45-L58 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Dictionary/RedisDictionary.php | RedisDictionary.getLanguagesByWord | public function getLanguagesByWord($word)
{
$word = mb_strtolower($word, mb_detect_encoding($word));
if ($this->redis->exists($word)) {
return unserialize($this->redis->get($word));
}
return null;
} | php | public function getLanguagesByWord($word)
{
$word = mb_strtolower($word, mb_detect_encoding($word));
if ($this->redis->exists($word)) {
return unserialize($this->redis->get($word));
}
return null;
} | {@inheritDoc} | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Dictionary/RedisDictionary.php#L37-L46 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Dictionary/RedisDictionary.php | RedisDictionary.addWord | public function addWord($language, $word)
{
$word = mb_strtolower($word, mb_detect_encoding($word));
if ($this->redis->exists($word)) {
$languages = unserialize($this->redis->get($word));
if (!in_array($language, $languages)) {
$languages[] = $language;
}
} else {
$languages = array($language);
}
$this->redis->set($word, serialize($languages));
return $this;
} | php | public function addWord($language, $word)
{
$word = mb_strtolower($word, mb_detect_encoding($word));
if ($this->redis->exists($word)) {
$languages = unserialize($this->redis->get($word));
if (!in_array($language, $languages)) {
$languages[] = $language;
}
} else {
$languages = array($language);
}
$this->redis->set($word, serialize($languages));
return $this;
} | {@inheritDoc} | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Dictionary/RedisDictionary.php#L51-L68 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Dictionary/RedisDictionary.php | RedisDictionary.removeWord | public function removeWord($language, $word)
{
$word = mb_strtolower($word, mb_detect_encoding($word));
if ($this->redis->exists($word)) {
$languages = unserialize($this->redis->get($word));
if (false !== $index = array_search($language, $languages)) {
unset ($languages[$index]);
if (!count($languages)) {
$this->redis->del($word);
} else {
$this->redis->set($word, serialize($languages));
}
}
}
return $this;
} | php | public function removeWord($language, $word)
{
$word = mb_strtolower($word, mb_detect_encoding($word));
if ($this->redis->exists($word)) {
$languages = unserialize($this->redis->get($word));
if (false !== $index = array_search($language, $languages)) {
unset ($languages[$index]);
if (!count($languages)) {
$this->redis->del($word);
} else {
$this->redis->set($word, serialize($languages));
}
}
}
return $this;
} | {@inheritDoc} | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Dictionary/RedisDictionary.php#L73-L92 |
AntonyThorpe/consumer | src/BulkLoaderResult.php | BulkLoaderResult.getUpdated | public function getUpdated()
{
$set = new ArrayList();
foreach ($this->updated as $arrItem) {
$set->push(ArrayData::create($arrItem));
}
return $set;
} | php | public function getUpdated()
{
$set = new ArrayList();
foreach ($this->updated as $arrItem) {
$set->push(ArrayData::create($arrItem));
}
return $set;
} | Return all updated objects
@return \SilverStripe\ORM\ArrayList | https://github.com/AntonyThorpe/consumer/blob/c9f464b901c09ab0bfbb62c94589637363af7bf0/src/BulkLoaderResult.php#L122-L129 |
AntonyThorpe/consumer | src/BulkLoaderResult.php | BulkLoaderResult.getDeleted | public function getDeleted()
{
$set = new ArrayList();
foreach ($this->deleted as $arrItem) {
$set->push(ArrayData::create($arrItem));
}
return $set;
} | php | public function getDeleted()
{
$set = new ArrayList();
foreach ($this->deleted as $arrItem) {
$set->push(ArrayData::create($arrItem));
}
return $set;
} | Return all deleted objects
@return \SilverStripe\ORM\ArrayList | https://github.com/AntonyThorpe/consumer/blob/c9f464b901c09ab0bfbb62c94589637363af7bf0/src/BulkLoaderResult.php#L135-L142 |
AntonyThorpe/consumer | src/BulkLoaderResult.php | BulkLoaderResult.getData | public function getData()
{
$data = new ArrayList();
if ($this->CreatedCount()) {
$data->push(ArrayData::create(array("Title" => _t('Consumer.CREATED', 'Created'))));
$data->merge($this->getCreated());
}
if ($this->UpdatedCount()) {
$data->push(ArrayData::create(array("Title" => _t('Consumer.UPDATED', 'Updated'))));
$data->merge($this->getUpdated());
}
if ($this->DeletedCount()) {
$data->push(ArrayData::create(array("Title" => _t('Consumer.DELETED', 'Deleted'))));
$data->merge($this->$this->getDeleted());
}
return $data;
} | php | public function getData()
{
$data = new ArrayList();
if ($this->CreatedCount()) {
$data->push(ArrayData::create(array("Title" => _t('Consumer.CREATED', 'Created'))));
$data->merge($this->getCreated());
}
if ($this->UpdatedCount()) {
$data->push(ArrayData::create(array("Title" => _t('Consumer.UPDATED', 'Updated'))));
$data->merge($this->getUpdated());
}
if ($this->DeletedCount()) {
$data->push(ArrayData::create(array("Title" => _t('Consumer.DELETED', 'Deleted'))));
$data->merge($this->$this->getDeleted());
}
return $data;
} | Prepare the boby for an email or build task
@return \SilverStripe\ORM\ArrayList | https://github.com/AntonyThorpe/consumer/blob/c9f464b901c09ab0bfbb62c94589637363af7bf0/src/BulkLoaderResult.php#L148-L164 |
AntonyThorpe/consumer | src/BulkLoaderResult.php | BulkLoaderResult.getChangedFields | protected function getChangedFields($obj)
{
$changedFields = $obj->getChangedFields(true, 2);
foreach ($changedFields as $key => $value) {
$changedFields[$key]['before'] = '(' . gettype($value['before']) . ') ' . $value['before'];
$changedFields[$key]['after'] = '(' . gettype($value['after']) . ') ' . $value['after'];
unset($changedFields[$key]['level']);
}
return $changedFields;
} | php | protected function getChangedFields($obj)
{
$changedFields = $obj->getChangedFields(true, 2);
foreach ($changedFields as $key => $value) {
$changedFields[$key]['before'] = '(' . gettype($value['before']) . ') ' . $value['before'];
$changedFields[$key]['after'] = '(' . gettype($value['after']) . ') ' . $value['after'];
unset($changedFields[$key]['level']);
}
return $changedFields;
} | Modelled on the getChangedFields of DataObject, with the addition of the variable's type
@param \SilverStripe\ORM\DataObject $obj
@return array The before/after changes of each field | https://github.com/AntonyThorpe/consumer/blob/c9f464b901c09ab0bfbb62c94589637363af7bf0/src/BulkLoaderResult.php#L209-L218 |
mojopollo/laravel-helpers | src/Mojopollo/Helpers/FileHelper.php | FileHelper.directoryFiles | public function directoryFiles($path)
{
$contents = [];
// Scan directory
$directoryFiles = scandir($path);
foreach ($directoryFiles as $index => $filePath) {
// Ommit . and ..
if ( ! in_array($filePath, ['.', '..'])) {
// Check if this is a directory
if (is_dir($path . DIRECTORY_SEPARATOR . $filePath)) {
// Rescan and get files in this directory
$contents = array_merge($contents, self::directoryFiles($path . DIRECTORY_SEPARATOR . $filePath));
} else {
// Add file to contens array
$contents[] = $path . DIRECTORY_SEPARATOR . $filePath;
}
}
}
return $contents;
} | php | public function directoryFiles($path)
{
$contents = [];
// Scan directory
$directoryFiles = scandir($path);
foreach ($directoryFiles as $index => $filePath) {
// Ommit . and ..
if ( ! in_array($filePath, ['.', '..'])) {
// Check if this is a directory
if (is_dir($path . DIRECTORY_SEPARATOR . $filePath)) {
// Rescan and get files in this directory
$contents = array_merge($contents, self::directoryFiles($path . DIRECTORY_SEPARATOR . $filePath));
} else {
// Add file to contens array
$contents[] = $path . DIRECTORY_SEPARATOR . $filePath;
}
}
}
return $contents;
} | Return an array of files with their full paths contained in a directory and its subdirectories
@param string $path path to directtory
@return array full paths of directory files | https://github.com/mojopollo/laravel-helpers/blob/0becb5e0f4202a0f489fb5e384c01dacb8f29dc5/src/Mojopollo/Helpers/FileHelper.php#L12-L39 |
ben-gibson/foursquare-venue-client | src/Client.php | Client.simple | public static function simple(Configuration $configuration, VenueFactory $venueFactory)
{
return new static(
$configuration,
new HttpMethodsClient(HttpClientDiscovery::find(), MessageFactoryDiscovery::find()),
$venueFactory
);
} | php | public static function simple(Configuration $configuration, VenueFactory $venueFactory)
{
return new static(
$configuration,
new HttpMethodsClient(HttpClientDiscovery::find(), MessageFactoryDiscovery::find()),
$venueFactory
);
} | Convenience factory method creating a standard Client configuration.
@param Configuration $configuration
@param VenueFactory $venueFactory
@return static | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Client.php#L50-L57 |
ben-gibson/foursquare-venue-client | src/Client.php | Client.getVenue | public function getVenue(Identifier $identifier)
{
$url = $this->getUrl(sprintf('venues/%s', urlencode($identifier)));
$response = $this->httpClient->get($url, $this->getDefaultHeaders());
$content = $this->parseResponse($response);
if (!isset($content->response->venue)) {
throw InvalidResponseException::invalidResponseBody($response, 'response.venue');
}
return $this->venueFactory->create(new Description($content->response->venue));
} | php | public function getVenue(Identifier $identifier)
{
$url = $this->getUrl(sprintf('venues/%s', urlencode($identifier)));
$response = $this->httpClient->get($url, $this->getDefaultHeaders());
$content = $this->parseResponse($response);
if (!isset($content->response->venue)) {
throw InvalidResponseException::invalidResponseBody($response, 'response.venue');
}
return $this->venueFactory->create(new Description($content->response->venue));
} | Get a venue by its unique identifier.
@param Identifier $identifier The venue identifier.
@return Venue | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Client.php#L66-L79 |
ben-gibson/foursquare-venue-client | src/Client.php | Client.search | public function search(Search $options)
{
$url = $this->getUrl('venues/search', $options->parametrise());
$response = $this->httpClient->get($url, $this->getDefaultHeaders());
$content = $this->parseResponse($response);
if (!isset($content->response->venues)) {
throw InvalidResponseException::invalidResponseBody($response, 'response.venues');
}
return array_map(function (\stdClass $venueDescription) {
return $this->venueFactory->create(new Description($venueDescription));
}, $content->response->venues);
} | php | public function search(Search $options)
{
$url = $this->getUrl('venues/search', $options->parametrise());
$response = $this->httpClient->get($url, $this->getDefaultHeaders());
$content = $this->parseResponse($response);
if (!isset($content->response->venues)) {
throw InvalidResponseException::invalidResponseBody($response, 'response.venues');
}
return array_map(function (\stdClass $venueDescription) {
return $this->venueFactory->create(new Description($venueDescription));
}, $content->response->venues);
} | Search venues.
@param Search $options The search options.
@return Venue[] | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Client.php#L88-L103 |
ben-gibson/foursquare-venue-client | src/Client.php | Client.explore | public function explore(Explore $options)
{
$url = $this->getUrl('venues/explore', $options->parametrise());
$response = $this->httpClient->get($url, $this->getDefaultHeaders());
$content = $this->parseResponse($response);
if (!isset($content->response->groups[0]->items)) {
throw InvalidResponseException::invalidResponseBody($response, 'response.groups[0].items');
}
return array_map(function (\stdClass $itemDescription) {
return $this->venueFactory->create(new Description($itemDescription->venue));
}, $content->response->groups[0]->items);
} | php | public function explore(Explore $options)
{
$url = $this->getUrl('venues/explore', $options->parametrise());
$response = $this->httpClient->get($url, $this->getDefaultHeaders());
$content = $this->parseResponse($response);
if (!isset($content->response->groups[0]->items)) {
throw InvalidResponseException::invalidResponseBody($response, 'response.groups[0].items');
}
return array_map(function (\stdClass $itemDescription) {
return $this->venueFactory->create(new Description($itemDescription->venue));
}, $content->response->groups[0]->items);
} | Explore venues.
@param Explore $options The explore options.
@return Venue[] | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Client.php#L112-L127 |
ben-gibson/foursquare-venue-client | src/Client.php | Client.parseResponse | private function parseResponse(ResponseInterface $response)
{
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
throw new ClientErrorException($response);
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
throw new ServerErrorException($response);
}
$response->getBody()->rewind();
$result = json_decode($response->getBody()->getContents());
if ($result === null) {
throw InvalidResponseException::failedToDecodeResponse($response, json_last_error_msg());
}
return $result;
} | php | private function parseResponse(ResponseInterface $response)
{
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
throw new ClientErrorException($response);
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
throw new ServerErrorException($response);
}
$response->getBody()->rewind();
$result = json_decode($response->getBody()->getContents());
if ($result === null) {
throw InvalidResponseException::failedToDecodeResponse($response, json_last_error_msg());
}
return $result;
} | Parse a response.
@param ResponseInterface $response The response to parse.
@throws ClientErrorException Thrown when a 4xx response status is returned.
@throws ServerErrorException Thrown when a 5xx response status is returned.
@throws InvalidResponseException Thrown when an invalid response body is encountered.
@return mixed | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Client.php#L164-L183 |
ben-gibson/foursquare-venue-client | src/Client.php | Client.getUrl | private function getUrl($path, $parameters = [])
{
$url = sprintf(
'%s/v%d/%s?client_id=%s&client_secret=%s&v=%s%s',
$this->configuration->getBasePath(),
urlencode($this->configuration->getVersion()),
trim($path, '/'),
urlencode($this->configuration->getClientId()),
urlencode($this->configuration->getClientSecret()),
urlencode($this->configuration->getVersionedDate()),
$this->parseParameters($parameters)
);
return $url;
} | php | private function getUrl($path, $parameters = [])
{
$url = sprintf(
'%s/v%d/%s?client_id=%s&client_secret=%s&v=%s%s',
$this->configuration->getBasePath(),
urlencode($this->configuration->getVersion()),
trim($path, '/'),
urlencode($this->configuration->getClientId()),
urlencode($this->configuration->getClientSecret()),
urlencode($this->configuration->getVersionedDate()),
$this->parseParameters($parameters)
);
return $url;
} | Get the API url for a given path.
@param string $path The path.
@param array $parameters The query parameters to include.
@return string | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Client.php#L193-L207 |
ben-gibson/foursquare-venue-client | src/Client.php | Client.parseParameters | private function parseParameters(array $parameters)
{
if (empty($parameters)) {
return '';
}
$parameters = implode('&', array_map(
function ($value, $key) {
return sprintf('%s=%s', $key, urlencode($value));
},
$parameters,
array_keys($parameters)
));
return "&{$parameters}";
} | php | private function parseParameters(array $parameters)
{
if (empty($parameters)) {
return '';
}
$parameters = implode('&', array_map(
function ($value, $key) {
return sprintf('%s=%s', $key, urlencode($value));
},
$parameters,
array_keys($parameters)
));
return "&{$parameters}";
} | Parse an array of parameters to their string representation.
@param array $parameters
@return string | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Client.php#L228-L243 |
SURFnet/yubikey-api-client | src/Service/VerificationService.php | VerificationService.parseYubicoResponse | private function parseYubicoResponse($response)
{
$lines = array_filter(explode("\r\n", $response));
$responseArray = array();
foreach ($lines as $line) {
list($key, $value) = explode('=', $line, 2);
$responseArray[$key] = $value;
}
return $responseArray;
} | php | private function parseYubicoResponse($response)
{
$lines = array_filter(explode("\r\n", $response));
$responseArray = array();
foreach ($lines as $line) {
list($key, $value) = explode('=', $line, 2);
$responseArray[$key] = $value;
}
return $responseArray;
} | Parses the response.
@param string $response
@return array | https://github.com/SURFnet/yubikey-api-client/blob/bbcb6340c89c5bcecf2f9258390cb9dfe2b87358/src/Service/VerificationService.php#L110-L122 |
slickframework/form | src/Renderer/Input.php | Input.render | public function render($context = [])
{
if ($element = $this->getElement()) {
$class = $element->getAttribute('class', false);
$class .= $class
? ' form-control'
: 'form-control';
$this->getElement()->setAttribute('class', $class);
}
return parent::render($context);
} | php | public function render($context = [])
{
if ($element = $this->getElement()) {
$class = $element->getAttribute('class', false);
$class .= $class
? ' form-control'
: 'form-control';
$this->getElement()->setAttribute('class', $class);
}
return parent::render($context);
} | Render the HTML element in the provided context
@param array $context
@return string The HTML string output | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Renderer/Input.php#L32-L43 |
phpalchemy/phpalchemy | Alchemy/Component/WebAssets/File.php | File.getMimeType | public function getMimeType()
{
if (array_key_exists($this->getExtension(), self::$mimeType)) {
return self::$mimeType[$this->getExtension()];
}
if (class_exists('finfo')) {
$finfo = new \finfo;
$mimeType = $finfo->file($this->getPathname(), FILEINFO_MIME);
if (preg_match('/([\w\-]+\/[\w\-]+); charset=(\w+)/', $mimeType, $match)) {
return $match[1];
}
}
if (function_exists('mime_content_type')) {
return mime_content_type($this->getPathname());
}
return 'application/octet-stream';
} | php | public function getMimeType()
{
if (array_key_exists($this->getExtension(), self::$mimeType)) {
return self::$mimeType[$this->getExtension()];
}
if (class_exists('finfo')) {
$finfo = new \finfo;
$mimeType = $finfo->file($this->getPathname(), FILEINFO_MIME);
if (preg_match('/([\w\-]+\/[\w\-]+); charset=(\w+)/', $mimeType, $match)) {
return $match[1];
}
}
if (function_exists('mime_content_type')) {
return mime_content_type($this->getPathname());
}
return 'application/octet-stream';
} | Returns the mime type of the file. (improved by erik)
The mime type is guessed using the functions finfo(), mime_content_type()
and the system binary "file" (in this order), depending on which of those
is available on the current operating system.
@author Erik Amaru Ortiz <[email protected]>
@return string|null The guessed mime type (i.e. "application/pdf") | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Component/WebAssets/File.php#L125-L145 |
antaresproject/sample_module | src/Customfields/GenderField.php | GenderField.getValue | public function getValue()
{
if (is_null($this->model->id)) {
return false;
}
$model = $this->getModel($this->model);
return !is_null($model) ? $model->value : false;
} | php | public function getValue()
{
if (is_null($this->model->id)) {
return false;
}
$model = $this->getModel($this->model);
return !is_null($model) ? $model->value : false;
} | {@inheritdoc} | https://github.com/antaresproject/sample_module/blob/aceab14f392c25e32729018518e9d6b4e6fe23db/src/Customfields/GenderField.php#L100-L107 |
slickframework/form | src/Input/Validator/RequiredUpload.php | RequiredUpload.validates | public function validates($value, $context = [])
{
$valid = true;
/** @var File $input */
$input = $context['input'];
/** @var UploadedFileInterface $file */
$file = $input->getValue();
if ($file->getError() == UPLOAD_ERR_NO_FILE) {
$valid = false;
$this->addMessage(
$this->messageTemplate,
$this->uploadErrors[$file->getError()]
);
}
return $valid;
} | php | public function validates($value, $context = [])
{
$valid = true;
/** @var File $input */
$input = $context['input'];
/** @var UploadedFileInterface $file */
$file = $input->getValue();
if ($file->getError() == UPLOAD_ERR_NO_FILE) {
$valid = false;
$this->addMessage(
$this->messageTemplate,
$this->uploadErrors[$file->getError()]
);
}
return $valid;
} | Returns true if and only if $value meets the validation requirements
The context specified can be used in the validation process so that
the same value can be valid or invalid depending on that data.
@param mixed $value
@param array|mixed|File $context
@return bool | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/Validator/RequiredUpload.php#L57-L72 |
eloquent/endec | src/Uri/UriEncodeTransform.php | UriEncodeTransform.transform | public function transform($data, &$context, $isEnd = false)
{
return array(rawurlencode($data), strlen($data), null);
} | php | public function transform($data, &$context, $isEnd = false)
{
return array(rawurlencode($data), strlen($data), null);
} | Transform the supplied data.
This method may transform only part of the supplied data. The return
value includes information about how much data was actually consumed. The
transform can be forced to consume all data by passing a boolean true as
the $isEnd argument.
The $context argument will initially be null, but any value assigned to
this variable will persist until the stream transformation is complete.
It can be used as a place to store state, such as a buffer.
It is guaranteed that this method will be called with $isEnd = true once,
and only once, at the end of the stream transformation.
@param string $data The data to transform.
@param mixed &$context An arbitrary context value.
@param boolean $isEnd True if all supplied data must be transformed.
@return tuple<string,integer,mixed> A 3-tuple of the transformed data, the number of bytes consumed, and any resulting error. | https://github.com/eloquent/endec/blob/90043a26439739d6bac631cc57dab3ecf5cafdc3/src/Uri/UriEncodeTransform.php#L58-L61 |
bruno-barros/w.eloquent-framework | src/weloquent/Plugins/PluginsLoader.php | PluginsLoader.bootRequired | public static function bootRequired()
{
// on test do not load plugins
if(self::isUnableToRunPlugins())
{
return;
}
foreach (self::$required as $plugin)
{
require_once __DIR__ . DS . $plugin;
}
} | php | public static function bootRequired()
{
// on test do not load plugins
if(self::isUnableToRunPlugins())
{
return;
}
foreach (self::$required as $plugin)
{
require_once __DIR__ . DS . $plugin;
}
} | Load required plugins | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Plugins/PluginsLoader.php#L46-L59 |
bruno-barros/w.eloquent-framework | src/weloquent/Plugins/PluginsLoader.php | PluginsLoader.loadFromPath | public static function loadFromPath($path)
{
// on test do not load plugins
if(self::isUnableToRunPlugins())
{
return;
}
if (!file_exists($path))
{
throw new InvalidArgumentException("The path [{$path}] doesn't exist to load plugins.");
}
$plugins = require $path;
foreach ($plugins as $plugin)
{
if (array_key_exists($plugin, self::$lookup))
{
$plugin = __DIR__ . DS . self::$lookup[$plugin];
}
if (file_exists($plugin))
{
require_once $plugin;
}
}
} | php | public static function loadFromPath($path)
{
// on test do not load plugins
if(self::isUnableToRunPlugins())
{
return;
}
if (!file_exists($path))
{
throw new InvalidArgumentException("The path [{$path}] doesn't exist to load plugins.");
}
$plugins = require $path;
foreach ($plugins as $plugin)
{
if (array_key_exists($plugin, self::$lookup))
{
$plugin = __DIR__ . DS . self::$lookup[$plugin];
}
if (file_exists($plugin))
{
require_once $plugin;
}
}
} | Require plugins based on an array of paths
@param $path | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Plugins/PluginsLoader.php#L66-L94 |
bruno-barros/w.eloquent-framework | src/weloquent/Plugins/PluginsLoader.php | PluginsLoader.isUnableToRunPlugins | private static function isUnableToRunPlugins()
{
if (defined('WELOQUENT_TEST_ENV')
|| defined('WP_INSTALLING')
|| (defined('WP_USE_THEMES') && WP_USE_THEMES === false)
|| (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST === true)
)
{
return true;
}
return false;
} | php | private static function isUnableToRunPlugins()
{
if (defined('WELOQUENT_TEST_ENV')
|| defined('WP_INSTALLING')
|| (defined('WP_USE_THEMES') && WP_USE_THEMES === false)
|| (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST === true)
)
{
return true;
}
return false;
} | Check if is on test or installing WordPress
or not using themes (typically running inside Laravel)
@return bool | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Plugins/PluginsLoader.php#L102-L114 |
romeOz/rock-cache | src/Memcached.php | Memcached.setTags | protected function setTags($key, array $tags = [])
{
if (empty($tags)) {
return;
}
foreach ($this->prepareTags($tags) as $tag) {
if (($keys = $this->storage->get($tag)) !== false) {
$keys = $this->unserialize($keys);
if (in_array($key, $keys, true)) {
continue;
}
$keys[] = $key;
$this->setInternal($tag, $this->serialize($keys), 0);
continue;
}
$this->setInternal($tag, $this->serialize((array)$key), 0);
}
} | php | protected function setTags($key, array $tags = [])
{
if (empty($tags)) {
return;
}
foreach ($this->prepareTags($tags) as $tag) {
if (($keys = $this->storage->get($tag)) !== false) {
$keys = $this->unserialize($keys);
if (in_array($key, $keys, true)) {
continue;
}
$keys[] = $key;
$this->setInternal($tag, $this->serialize($keys), 0);
continue;
}
$this->setInternal($tag, $this->serialize((array)$key), 0);
}
} | Sets a tags
@param string $key key of cache
@param array $tags list of tags | https://github.com/romeOz/rock-cache/blob/bbd146ee323e8cc1fb11dc1803215c3656e02c57/src/Memcached.php#L275-L293 |
3ev/wordpress-core | src/Tev/Term/Repository/TermRepository.php | TermRepository.getByTaxonomy | public function getByTaxonomy($taxonomy)
{
if (!($taxonomy instanceof Taxonomy)) {
$taxonomy = $this->taxonomyFactory->create($taxonomy);
}
return $this->convertTermsArray(get_terms($taxonomy->getName(), array(
'hide_empty' => false
)), $taxonomy);
} | php | public function getByTaxonomy($taxonomy)
{
if (!($taxonomy instanceof Taxonomy)) {
$taxonomy = $this->taxonomyFactory->create($taxonomy);
}
return $this->convertTermsArray(get_terms($taxonomy->getName(), array(
'hide_empty' => false
)), $taxonomy);
} | Get all terms in the given taxonomy.
@param string|\Tev\Taxonomy\Model\Taxonomy $taxonomy Taxonomy object or name
@return \Tev\Term\Model\Term[] | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Term/Repository/TermRepository.php#L51-L60 |
3ev/wordpress-core | src/Tev/Term/Repository/TermRepository.php | TermRepository.convertTermsArray | private function convertTermsArray($terms, Taxonomy $taxonomy)
{
$res = array();
foreach ($terms as $t) {
$res[] = $this->termFactory->create($t, $taxonomy);
}
return $res;
} | php | private function convertTermsArray($terms, Taxonomy $taxonomy)
{
$res = array();
foreach ($terms as $t) {
$res[] = $this->termFactory->create($t, $taxonomy);
}
return $res;
} | Convert an array of Wordpress term objects to array of Term objects.
@param \stdClass[] $terms Wordpress term objects
@param \Tev\Taxonomy\Model\Taxonomy $taxonomy Parent taxonomy
@return \Tev\Term\Model\Term[] Term objects | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Term/Repository/TermRepository.php#L69-L78 |
pinguo/php-i18n | src/MessageFormatter.php | MessageFormatter.format | public function format($pattern, $params, $language)
{
$this->_errorCode = 0;
$this->_errorMessage = '';
if ($params === []) {
return $pattern;
}
if (! class_exists('MessageFormatter', false)) {
return $this->fallbackFormat($pattern, $params, $language);
}
// replace named arguments (https://github.com/yiisoft/yii2/issues/9678)
$pattern = $this->replaceNamedArguments($pattern, $params, $newParams);
$params = $newParams;
$formatter = new \MessageFormatter($language, $pattern);
if ($formatter === null) {
$this->_errorCode = intl_get_error_code();
$this->_errorMessage = 'Message pattern is invalid: ' . intl_get_error_message();
return false;
}
$result = $formatter->format($params);
if ($result === false) {
$this->_errorCode = $formatter->getErrorCode();
$this->_errorMessage = $formatter->getErrorMessage();
return false;
} else {
return $result;
}
} | php | public function format($pattern, $params, $language)
{
$this->_errorCode = 0;
$this->_errorMessage = '';
if ($params === []) {
return $pattern;
}
if (! class_exists('MessageFormatter', false)) {
return $this->fallbackFormat($pattern, $params, $language);
}
// replace named arguments (https://github.com/yiisoft/yii2/issues/9678)
$pattern = $this->replaceNamedArguments($pattern, $params, $newParams);
$params = $newParams;
$formatter = new \MessageFormatter($language, $pattern);
if ($formatter === null) {
$this->_errorCode = intl_get_error_code();
$this->_errorMessage = 'Message pattern is invalid: ' . intl_get_error_message();
return false;
}
$result = $formatter->format($params);
if ($result === false) {
$this->_errorCode = $formatter->getErrorCode();
$this->_errorMessage = $formatter->getErrorMessage();
return false;
} else {
return $result;
}
} | 格式化
@param string $pattern 规则模式
@param array $params 参数
@param string $language 语言
@return bool|string | https://github.com/pinguo/php-i18n/blob/2fc7c563dd3c8781d374c9e30f62bdb13d33dde8/src/MessageFormatter.php#L44-L77 |
pinguo/php-i18n | src/MessageFormatter.php | MessageFormatter.replaceNamedArguments | private function replaceNamedArguments($pattern, $givenParams, &$resultingParams, &$map = [])
{
if (($tokens = self::tokenizePattern($pattern)) === false) {
return false;
}
foreach ($tokens as $i => $token) {
if (! is_array($token)) {
continue;
}
$param = trim($token[0]);
if (isset($givenParams[$param])) {
// if param is given, replace it with a number
if (! isset($map[$param])) {
$map[$param] = count($map);
// make sure only used params are passed to format method
$resultingParams[$map[$param]] = $givenParams[$param];
}
$token[0] = $map[$param];
$quote = '';
} else {
// quote unused token
$quote = "'";
}
$type = isset($token[1]) ? trim($token[1]) : 'none';
// replace plural and select format recursively
if ($type === 'plural' || $type === 'select') {
if (! isset($token[2])) {
return false;
}
if (($subtokens = self::tokenizePattern($token[2])) === false) {
return false;
}
$c = count($subtokens);
for ($k = 0; $k + 1 < $c; $k++) {
if (is_array($subtokens[$k]) || ! is_array($subtokens[++$k])) {
return false;
}
$subpattern = $this->replaceNamedArguments(implode(',', $subtokens[$k]), $givenParams,
$resultingParams, $map);
$subtokens[$k] = $quote . '{' . $quote . $subpattern . $quote . '}' . $quote;
}
$token[2] = implode('', $subtokens);
}
$tokens[$i] = $quote . '{' . $quote . implode(',', $token) . $quote . '}' . $quote;
}
return implode('', $tokens);
} | php | private function replaceNamedArguments($pattern, $givenParams, &$resultingParams, &$map = [])
{
if (($tokens = self::tokenizePattern($pattern)) === false) {
return false;
}
foreach ($tokens as $i => $token) {
if (! is_array($token)) {
continue;
}
$param = trim($token[0]);
if (isset($givenParams[$param])) {
// if param is given, replace it with a number
if (! isset($map[$param])) {
$map[$param] = count($map);
// make sure only used params are passed to format method
$resultingParams[$map[$param]] = $givenParams[$param];
}
$token[0] = $map[$param];
$quote = '';
} else {
// quote unused token
$quote = "'";
}
$type = isset($token[1]) ? trim($token[1]) : 'none';
// replace plural and select format recursively
if ($type === 'plural' || $type === 'select') {
if (! isset($token[2])) {
return false;
}
if (($subtokens = self::tokenizePattern($token[2])) === false) {
return false;
}
$c = count($subtokens);
for ($k = 0; $k + 1 < $c; $k++) {
if (is_array($subtokens[$k]) || ! is_array($subtokens[++$k])) {
return false;
}
$subpattern = $this->replaceNamedArguments(implode(',', $subtokens[$k]), $givenParams,
$resultingParams, $map);
$subtokens[$k] = $quote . '{' . $quote . $subpattern . $quote . '}' . $quote;
}
$token[2] = implode('', $subtokens);
}
$tokens[$i] = $quote . '{' . $quote . implode(',', $token) . $quote . '}' . $quote;
}
return implode('', $tokens);
} | 替换字符串中的参数
@param string $pattern
@param array $givenParams
@param array $resultingParams
@param array $map
@return bool|string | https://github.com/pinguo/php-i18n/blob/2fc7c563dd3c8781d374c9e30f62bdb13d33dde8/src/MessageFormatter.php#L150-L197 |
pinguo/php-i18n | src/MessageFormatter.php | MessageFormatter.parseToken | private function parseToken($token, $args, $locale)
{
// parsing pattern based on ICU grammar:
// http://icu-project.org/apiref/icu4c/classMessageFormat.html#details
$charset = 'UTF-8';
$param = trim($token[0]);
if (isset($args[$param])) {
$arg = $args[$param];
} else {
return '{' . implode(',', $token) . '}';
}
$type = isset($token[1]) ? trim($token[1]) : 'none';
switch ($type) {
case 'date':
case 'time':
case 'spellout':
case 'ordinal':
case 'duration':
case 'choice':
case 'selectordinal':
throw new \Exception("Message format '$type' is not supported. You have to install PHP intl extension to use this feature.");
case 'number':
if (is_int($arg) && (! isset($token[2]) || trim($token[2]) === 'integer')) {
return $arg;
}
throw new \Exception("Message format 'number' is only supported for integer values. You have to install PHP intl extension to use this feature.");
case 'none':
return $arg;
case 'select':
/** http://icu-project.org/apiref/icu4c/classicu_1_1SelectFormat.html
* selectStyle = (selector '{' message '}')+
*/
if (! isset($token[2])) {
return false;
}
$select = self::tokenizePattern($token[2]);
$c = count($select);
$message = false;
for ($i = 0; $i + 1 < $c; $i++) {
if (is_array($select[$i]) || ! is_array($select[$i + 1])) {
return false;
}
$selector = trim($select[$i++]);
if ($message === false && $selector === 'other' || $selector == $arg) {
$message = implode(',', $select[$i]);
}
}
if ($message !== false) {
return $this->fallbackFormat($message, $args, $locale);
}
break;
case 'plural':
/* http://icu-project.org/apiref/icu4c/classicu_1_1PluralFormat.html
pluralStyle = [offsetValue] (selector '{' message '}')+
offsetValue = "offset:" number
selector = explicitValue | keyword
explicitValue = '=' number // adjacent, no white space in between
keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
message: see MessageFormat
*/
if (! isset($token[2])) {
return false;
}
$plural = self::tokenizePattern($token[2]);
$c = count($plural);
$message = false;
$offset = 0;
for ($i = 0; $i + 1 < $c; $i++) {
if (is_array($plural[$i]) || ! is_array($plural[$i + 1])) {
return false;
}
$selector = trim($plural[$i++]);
if ($i == 1 && strncmp($selector, 'offset:', 7) === 0) {
$offset = (int)trim(mb_substr($selector, 7,
($pos = mb_strpos(str_replace(["\n", "\r", "\t"], ' ', $selector), ' ', 7, $charset)) - 7,
$charset));
$selector = trim(mb_substr($selector, $pos + 1, null, $charset));
}
if ($message === false && $selector === 'other' ||
$selector[0] === '=' && (int)mb_substr($selector, 1, null, $charset) === $arg ||
$selector === 'one' && $arg - $offset == 1
) {
$message = implode(',', str_replace('#', $arg - $offset, $plural[$i]));
}
}
if ($message !== false) {
return $this->fallbackFormat($message, $args, $locale);
}
break;
}
return false;
} | php | private function parseToken($token, $args, $locale)
{
// parsing pattern based on ICU grammar:
// http://icu-project.org/apiref/icu4c/classMessageFormat.html#details
$charset = 'UTF-8';
$param = trim($token[0]);
if (isset($args[$param])) {
$arg = $args[$param];
} else {
return '{' . implode(',', $token) . '}';
}
$type = isset($token[1]) ? trim($token[1]) : 'none';
switch ($type) {
case 'date':
case 'time':
case 'spellout':
case 'ordinal':
case 'duration':
case 'choice':
case 'selectordinal':
throw new \Exception("Message format '$type' is not supported. You have to install PHP intl extension to use this feature.");
case 'number':
if (is_int($arg) && (! isset($token[2]) || trim($token[2]) === 'integer')) {
return $arg;
}
throw new \Exception("Message format 'number' is only supported for integer values. You have to install PHP intl extension to use this feature.");
case 'none':
return $arg;
case 'select':
/** http://icu-project.org/apiref/icu4c/classicu_1_1SelectFormat.html
* selectStyle = (selector '{' message '}')+
*/
if (! isset($token[2])) {
return false;
}
$select = self::tokenizePattern($token[2]);
$c = count($select);
$message = false;
for ($i = 0; $i + 1 < $c; $i++) {
if (is_array($select[$i]) || ! is_array($select[$i + 1])) {
return false;
}
$selector = trim($select[$i++]);
if ($message === false && $selector === 'other' || $selector == $arg) {
$message = implode(',', $select[$i]);
}
}
if ($message !== false) {
return $this->fallbackFormat($message, $args, $locale);
}
break;
case 'plural':
/* http://icu-project.org/apiref/icu4c/classicu_1_1PluralFormat.html
pluralStyle = [offsetValue] (selector '{' message '}')+
offsetValue = "offset:" number
selector = explicitValue | keyword
explicitValue = '=' number // adjacent, no white space in between
keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
message: see MessageFormat
*/
if (! isset($token[2])) {
return false;
}
$plural = self::tokenizePattern($token[2]);
$c = count($plural);
$message = false;
$offset = 0;
for ($i = 0; $i + 1 < $c; $i++) {
if (is_array($plural[$i]) || ! is_array($plural[$i + 1])) {
return false;
}
$selector = trim($plural[$i++]);
if ($i == 1 && strncmp($selector, 'offset:', 7) === 0) {
$offset = (int)trim(mb_substr($selector, 7,
($pos = mb_strpos(str_replace(["\n", "\r", "\t"], ' ', $selector), ' ', 7, $charset)) - 7,
$charset));
$selector = trim(mb_substr($selector, $pos + 1, null, $charset));
}
if ($message === false && $selector === 'other' ||
$selector[0] === '=' && (int)mb_substr($selector, 1, null, $charset) === $arg ||
$selector === 'one' && $arg - $offset == 1
) {
$message = implode(',', str_replace('#', $arg - $offset, $plural[$i]));
}
}
if ($message !== false) {
return $this->fallbackFormat($message, $args, $locale);
}
break;
}
return false;
} | Parses a token
@param array $token the token to parse
@param array $args arguments to replace
@param string $locale the locale
@return bool|string parsed token or false on failure
@throws \Exception when unsupported formatting is used. | https://github.com/pinguo/php-i18n/blob/2fc7c563dd3c8781d374c9e30f62bdb13d33dde8/src/MessageFormatter.php#L279-L372 |
acacha/forge-publish | src/Console/Commands/Traits/ChecksSSHConnection.php | ChecksSSHConnection.checkSSHConnection | protected function checkSSHConnection($server = null, $ssh_config_file = null, $verbose = false)
{
$server = $server ? $server : $this->hostNameForConfigFile();
$ssh_config_file = $ssh_config_file ? $ssh_config_file : $this->sshConfigFile();
if ($verbose) {
$this->info("timeout 10 ssh -F $ssh_config_file -q " . $server . ' exit; echo $?');
}
$ret = exec("timeout 10 ssh -F $ssh_config_file -q " . $server . ' "exit"; echo $?');
if ($ret == 0) {
return true;
}
return false;
} | php | protected function checkSSHConnection($server = null, $ssh_config_file = null, $verbose = false)
{
$server = $server ? $server : $this->hostNameForConfigFile();
$ssh_config_file = $ssh_config_file ? $ssh_config_file : $this->sshConfigFile();
if ($verbose) {
$this->info("timeout 10 ssh -F $ssh_config_file -q " . $server . ' exit; echo $?');
}
$ret = exec("timeout 10 ssh -F $ssh_config_file -q " . $server . ' "exit"; echo $?');
if ($ret == 0) {
return true;
}
return false;
} | Check SSH connection.
@return bool | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/Traits/ChecksSSHConnection.php#L50-L63 |
acacha/forge-publish | src/Console/Commands/Traits/ChecksSSHConnection.php | ChecksSSHConnection.abortIfNoSSHConnection | protected function abortIfNoSSHConnection($server = null)
{
$server = $server ? $server : $this->hostNameForConfigFile();
if (!$this->checkSSHConnection($server)) {
$this->error("SSH connection to server $server doesn't works. Please run php artisan publish:init or publish:ssh");
die();
}
} | php | protected function abortIfNoSSHConnection($server = null)
{
$server = $server ? $server : $this->hostNameForConfigFile();
if (!$this->checkSSHConnection($server)) {
$this->error("SSH connection to server $server doesn't works. Please run php artisan publish:init or publish:ssh");
die();
}
} | Abort if no SSH connection.
@return bool | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/Traits/ChecksSSHConnection.php#L70-L77 |
schpill/thin | src/Load/Ini.php | Ini._loadIniFile | protected function _loadIniFile($filename)
{
$loaded = $this->_parseIniFile($filename);
$iniArray = array();
foreach ($loaded as $key => $data)
{
$parts = explode($this->_sectionSeparator, $key);
$thisSection = trim(Arrays::first($parts));
switch (count($parts)) {
case 1:
$iniArray[$thisSection] = $data;
break;
case 2:
$extendedSection = trim(Arrays::last($parts));
$iniArray[$thisSection] = array_merge(
array(
';extends' => $extendedSection
),
$data
);
break;
default:
throw new Exception("Section '$thisSection' may not extend multiple sections in $filename");
}
}
return $iniArray;
} | php | protected function _loadIniFile($filename)
{
$loaded = $this->_parseIniFile($filename);
$iniArray = array();
foreach ($loaded as $key => $data)
{
$parts = explode($this->_sectionSeparator, $key);
$thisSection = trim(Arrays::first($parts));
switch (count($parts)) {
case 1:
$iniArray[$thisSection] = $data;
break;
case 2:
$extendedSection = trim(Arrays::last($parts));
$iniArray[$thisSection] = array_merge(
array(
';extends' => $extendedSection
),
$data
);
break;
default:
throw new Exception("Section '$thisSection' may not extend multiple sections in $filename");
}
}
return $iniArray;
} | Load the ini file and preprocess the section separator (':' in the
section name (that is used for section extension) so that the resultant
array has the correct section names and the extension information is
stored in a sub-key called ';extends'. We use ';extends' as this can
never be a valid key name in an INI file that has been loaded using
parse_ini_file().
@param string $filename
@throws Exception
@return array | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Load/Ini.php#L173-L200 |
schpill/thin | src/Load/Ini.php | Ini._processSection | protected function _processSection($iniArray, $section, $config = array())
{
$thisSection = $iniArray[$section];
foreach ($thisSection as $key => $value) {
if (Inflector::lower($key) == ';extends') {
if (isset($iniArray[$value])) {
$this->_assertValidExtend($section, $value);
if (!$this->_skipExtends) {
$config = $this->_processSection(
$iniArray,
$value,
$config
);
}
} else {
throw new Exception("Parent section '$section' cannot be found");
}
} else {
$config = $this->_processKey(
$config,
$key,
$value
);
}
}
return $config;
} | php | protected function _processSection($iniArray, $section, $config = array())
{
$thisSection = $iniArray[$section];
foreach ($thisSection as $key => $value) {
if (Inflector::lower($key) == ';extends') {
if (isset($iniArray[$value])) {
$this->_assertValidExtend($section, $value);
if (!$this->_skipExtends) {
$config = $this->_processSection(
$iniArray,
$value,
$config
);
}
} else {
throw new Exception("Parent section '$section' cannot be found");
}
} else {
$config = $this->_processKey(
$config,
$key,
$value
);
}
}
return $config;
} | Process each element in the section and handle the ";extends" inheritance
key. Passes control to _processKey() to handle the nest separator
sub-property syntax that may be used within the key name.
@param array $iniArray
@param string $section
@param array $config
@throws Exception
@return array | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Load/Ini.php#L213-L241 |
schpill/thin | src/Load/Ini.php | Ini._processKey | protected function _processKey($config, $key, $value)
{
if (strpos($key, $this->_nestSeparator) !== false) {
$parts = explode($this->_nestSeparator, $key, 2);
if (strlen(Arrays::first($parts)) && strlen(Arrays::last($parts))) {
if (!isset($config[Arrays::first($parts)])) {
if (Arrays::first($parts) === '0' && !empty($config)) {
// convert the current values in $config into an array
$config = array(Arrays::first($parts) => $config);
} else {
$config[Arrays::first($parts)] = array();
}
} elseif (!Arrays::is($config[Arrays::first($parts)])) {
throw new Exception("Cannot create sub-key for '{Arrays::first($parts)}' as key already exists");
}
$config[Arrays::first($parts)] = $this->_processKey(
$config[Arrays::first($parts)],
Arrays::last($parts),
$value
);
} else {
throw new Exception("Invalid key '$key'");
}
} else {
$config[$key] = $value;
}
return $config;
} | php | protected function _processKey($config, $key, $value)
{
if (strpos($key, $this->_nestSeparator) !== false) {
$parts = explode($this->_nestSeparator, $key, 2);
if (strlen(Arrays::first($parts)) && strlen(Arrays::last($parts))) {
if (!isset($config[Arrays::first($parts)])) {
if (Arrays::first($parts) === '0' && !empty($config)) {
// convert the current values in $config into an array
$config = array(Arrays::first($parts) => $config);
} else {
$config[Arrays::first($parts)] = array();
}
} elseif (!Arrays::is($config[Arrays::first($parts)])) {
throw new Exception("Cannot create sub-key for '{Arrays::first($parts)}' as key already exists");
}
$config[Arrays::first($parts)] = $this->_processKey(
$config[Arrays::first($parts)],
Arrays::last($parts),
$value
);
} else {
throw new Exception("Invalid key '$key'");
}
} else {
$config[$key] = $value;
}
return $config;
} | Assign the key's value to the property list. Handles the
nest separator for sub-properties.
@param array $config
@param string $key
@param string $value
@throws Exception
@return array | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Load/Ini.php#L253-L280 |
phonetworks/pho-compiler | src/Pho/Compiler/Inspector.php | Inspector.assertParity | public function assertParity(): void
{
$ignored_classes = [];
$object_exists = false;
$actor_exists = false;
$locator = new ClassFileLocator($this->folder);
foreach ($locator as $file) {
$filename = str_replace($this->folder . DIRECTORY_SEPARATOR, '', $file->getRealPath());
foreach ($file->getClasses() as $class) {
$reflector = new \ReflectionClass($class);
$parent = $reflector->getParentClass()->getName();
$class_name = $reflector->getShortName();
switch($parent) {
case "Pho\Framework\Object":
$object_exists = true;
try {
$this->checkEdgeDir($class_name);
}
catch(Exceptions\AbsentEdgeDirImparityException $e) {
throw $e;
}
break;
case "Pho\Framework\Actor":
$actor_exists = true;
try {
$this->checkEdgeDir($class_name);
}
catch(Exceptions\AbsentEdgeDirImparityException $e) {
throw $e;
}
break;
case "Pho\Framework\Frame":
try {
$this->checkEdgeDir($class_name);
}
catch(Exceptions\AbsentEdgeDirImparityException $e) {
throw $e;
}
break;
default:
$ignored_classes[] = [
"filename" => $filename,
"classname" => $class_name
];
break;
}
}
}
if(!$object_exists) {
throw new Exceptions\MissingObjectImparityException($this->folder);
}
if(!$actor_exists) {
throw new Exceptions\MissingActorImparityException($this->folder);
}
} | php | public function assertParity(): void
{
$ignored_classes = [];
$object_exists = false;
$actor_exists = false;
$locator = new ClassFileLocator($this->folder);
foreach ($locator as $file) {
$filename = str_replace($this->folder . DIRECTORY_SEPARATOR, '', $file->getRealPath());
foreach ($file->getClasses() as $class) {
$reflector = new \ReflectionClass($class);
$parent = $reflector->getParentClass()->getName();
$class_name = $reflector->getShortName();
switch($parent) {
case "Pho\Framework\Object":
$object_exists = true;
try {
$this->checkEdgeDir($class_name);
}
catch(Exceptions\AbsentEdgeDirImparityException $e) {
throw $e;
}
break;
case "Pho\Framework\Actor":
$actor_exists = true;
try {
$this->checkEdgeDir($class_name);
}
catch(Exceptions\AbsentEdgeDirImparityException $e) {
throw $e;
}
break;
case "Pho\Framework\Frame":
try {
$this->checkEdgeDir($class_name);
}
catch(Exceptions\AbsentEdgeDirImparityException $e) {
throw $e;
}
break;
default:
$ignored_classes[] = [
"filename" => $filename,
"classname" => $class_name
];
break;
}
}
}
if(!$object_exists) {
throw new Exceptions\MissingObjectImparityException($this->folder);
}
if(!$actor_exists) {
throw new Exceptions\MissingActorImparityException($this->folder);
}
} | Validates the compiled schema directory.
@return void
@throws Exceptions\MissingObjectImparityException if there is no object node found.
@throws Exceptions\MissingActorImparityException if there is no actor node found.
@throws Exceptions\AbsentEdgeDirImparityException if the node does not have a directory for its edges. | https://github.com/phonetworks/pho-compiler/blob/9131c3ac55d163069aaf6808b7339345151c7280/src/Pho/Compiler/Inspector.php#L63-L117 |
phonetworks/pho-compiler | src/Pho/Compiler/Inspector.php | Inspector.checkEdgeDir | protected function checkEdgeDir(string $node_name): void
{
$dirname = $this->folder.DIRECTORY_SEPARATOR.$node_name."Out";
if(!file_exists($dirname)) {
throw new Exceptions\AbsentEdgeDirImparityException($dirname, $node_name);
}
} | php | protected function checkEdgeDir(string $node_name): void
{
$dirname = $this->folder.DIRECTORY_SEPARATOR.$node_name."Out";
if(!file_exists($dirname)) {
throw new Exceptions\AbsentEdgeDirImparityException($dirname, $node_name);
}
} | Checks if the node has a directory for its edges.
@param string $node_name The name of the node.
@return void
@throws Exceptions\AbsentEdgeDirImparityException if the node does not have a directory for its edges. | https://github.com/phonetworks/pho-compiler/blob/9131c3ac55d163069aaf6808b7339345151c7280/src/Pho/Compiler/Inspector.php#L128-L134 |
IftekherSunny/Planet-Framework | src/Sun/Console/Commands/MakeEvent.php | MakeEvent.handle | public function handle()
{
$eventName = $this->input->getArgument('name');
$eventNamespace = $this->getNamespace('Events', $eventName);
$eventStubs = $this->filesystem->get(__DIR__.'/../stubs/MakeEvent.txt');
$eventStubs = str_replace([ 'dummyEventName', 'dummyNamespace', '\\\\' ], [ basename($eventName), $eventNamespace, '\\' ], $eventStubs);
if(!file_exists($filename = app_path() ."/Events/{$eventName}.php")) {
$this->filesystem->create($filename, $eventStubs);
$this->info("{$eventName} has been created successfully.");
} else {
$this->info("{$eventName} already exists.");
}
} | php | public function handle()
{
$eventName = $this->input->getArgument('name');
$eventNamespace = $this->getNamespace('Events', $eventName);
$eventStubs = $this->filesystem->get(__DIR__.'/../stubs/MakeEvent.txt');
$eventStubs = str_replace([ 'dummyEventName', 'dummyNamespace', '\\\\' ], [ basename($eventName), $eventNamespace, '\\' ], $eventStubs);
if(!file_exists($filename = app_path() ."/Events/{$eventName}.php")) {
$this->filesystem->create($filename, $eventStubs);
$this->info("{$eventName} has been created successfully.");
} else {
$this->info("{$eventName} already exists.");
}
} | To handle console command | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/MakeEvent.php#L42-L58 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceTranslations.php | HCServiceTranslations.optimize | public function optimize (stdClass $data)
{
$data->translationFilePrefix = $this->stringWithUnderscore ($data->serviceURL);
$data->translationFilePrefix = $this->stringWithUnderscore ($data->translationFilePrefix);
$data->translationsLocation = $this->getTranslationPrefix ($data) . $data->translationFilePrefix;
return $data;
} | php | public function optimize (stdClass $data)
{
$data->translationFilePrefix = $this->stringWithUnderscore ($data->serviceURL);
$data->translationFilePrefix = $this->stringWithUnderscore ($data->translationFilePrefix);
$data->translationsLocation = $this->getTranslationPrefix ($data) . $data->translationFilePrefix;
return $data;
} | Optimizing Translations data
@param stdClass $data
@return stdClass | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceTranslations.php#L21-L29 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceTranslations.php | HCServiceTranslations.getServiceProviderNameSpace | private function getServiceProviderNameSpace (stdClass $item)
{
return json_decode (file_get_contents ($item->rootDirectory . 'app/' . HCNewService::CONFIG_PATH))->general->serviceProviderNameSpace;
} | php | private function getServiceProviderNameSpace (stdClass $item)
{
return json_decode (file_get_contents ($item->rootDirectory . 'app/' . HCNewService::CONFIG_PATH))->general->serviceProviderNameSpace;
} | Getting service provider namespace
@param $item
@return mixed | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceTranslations.php#L52-L55 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceTranslations.php | HCServiceTranslations.generate | public function generate (stdClass $service)
{
$this->createFileFromTemplate ([
"destination" => $service->rootDirectory . 'resources/lang/en/' . $service->translationFilePrefix . '.php',
"templateDestination" => __DIR__ . '/../templates/service/translations.hctpl',
"content" => [
"translations" => $this->gatherTranslations ($service),
],
]);
return $service->rootDirectory . 'resources/lang/en/' . $service->translationFilePrefix . '.php';
} | php | public function generate (stdClass $service)
{
$this->createFileFromTemplate ([
"destination" => $service->rootDirectory . 'resources/lang/en/' . $service->translationFilePrefix . '.php',
"templateDestination" => __DIR__ . '/../templates/service/translations.hctpl',
"content" => [
"translations" => $this->gatherTranslations ($service),
],
]);
return $service->rootDirectory . 'resources/lang/en/' . $service->translationFilePrefix . '.php';
} | Creating translation file
@param $service
@return string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceTranslations.php#L63-L74 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceTranslations.php | HCServiceTranslations.gatherTranslations | private function gatherTranslations (stdClass $service)
{
$output = '';
$tpl = file_get_contents (__DIR__ . '/../templates/shared/array.element.hctpl');
$line = str_replace ('{key}', 'page_title', $tpl);
$line = str_replace ('{value}', $service->serviceName, $line);
$output .= $line;
$output .= $this->gatherTranslationsFromModel ($service->mainModel, $tpl, array_merge ($this->getAutoFill (), ['id']));
if (isset($service->mainModel->multiLanguage))
$output .= $this->gatherTranslationsFromModel ($service->mainModel->multiLanguage, $tpl, array_merge ($this->getAutoFill (), ['id', 'language_code', 'record_id']));
return $output;
} | php | private function gatherTranslations (stdClass $service)
{
$output = '';
$tpl = file_get_contents (__DIR__ . '/../templates/shared/array.element.hctpl');
$line = str_replace ('{key}', 'page_title', $tpl);
$line = str_replace ('{value}', $service->serviceName, $line);
$output .= $line;
$output .= $this->gatherTranslationsFromModel ($service->mainModel, $tpl, array_merge ($this->getAutoFill (), ['id']));
if (isset($service->mainModel->multiLanguage))
$output .= $this->gatherTranslationsFromModel ($service->mainModel->multiLanguage, $tpl, array_merge ($this->getAutoFill (), ['id', 'language_code', 'record_id']));
return $output;
} | Gathering available translations
@param $service
@return string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceTranslations.php#L82-L96 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceTranslations.php | HCServiceTranslations.gatherTranslationsFromModel | private function gatherTranslationsFromModel (stdClass $model, string $tpl, array $skip)
{
$output = '';
if (array_key_exists ('columns', $model) && !empty($model->columns))
foreach ($model->columns as $column) {
if (in_array ($column->Field, $skip))
continue;
$line = str_replace ('{key}', $column->Field, $tpl);
$line = str_replace ('{value}', str_replace ("_", " ", ucfirst ($column->Field)), $line);
$output .= $line;
}
return $output;
} | php | private function gatherTranslationsFromModel (stdClass $model, string $tpl, array $skip)
{
$output = '';
if (array_key_exists ('columns', $model) && !empty($model->columns))
foreach ($model->columns as $column) {
if (in_array ($column->Field, $skip))
continue;
$line = str_replace ('{key}', $column->Field, $tpl);
$line = str_replace ('{value}', str_replace ("_", " ", ucfirst ($column->Field)), $line);
$output .= $line;
}
return $output;
} | Gathering fields from specific model
@param stdClass $model
@param string $tpl
@param array $skip
@return string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceTranslations.php#L106-L122 |
ajaxtown/eaglehorn_framework | src/Eaglehorn/worker/Time/Time.php | Time.timeAgo | function timeAgo($date)
{
if (empty($date)) {
return "No date provided";
}
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60", "60", "24", "7", "4.35", "12", "10");
$now = time();
$unix_date = strtotime($date);
// check validity of date
if (empty($unix_date)) {
return "Bad date";
}
// is it future date or past date
if ($now > $unix_date) {
$difference = $now - $unix_date;
$tense = "ago";
} else {
$difference = $unix_date - $now;
$tense = "from now";
}
for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if ($difference != 1) {
$periods[$j] .= "s";
}
return "$difference $periods[$j] {$tense}";
} | php | function timeAgo($date)
{
if (empty($date)) {
return "No date provided";
}
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60", "60", "24", "7", "4.35", "12", "10");
$now = time();
$unix_date = strtotime($date);
// check validity of date
if (empty($unix_date)) {
return "Bad date";
}
// is it future date or past date
if ($now > $unix_date) {
$difference = $now - $unix_date;
$tense = "ago";
} else {
$difference = $unix_date - $now;
$tense = "from now";
}
for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if ($difference != 1) {
$periods[$j] .= "s";
}
return "$difference $periods[$j] {$tense}";
} | Returns time difference in past tense.
Usage:
echo $this->time->timeAgo('2013-01-15 06:36:42');
@param string | date $date
@return string | https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/worker/Time/Time.php#L28-L77 |
ajaxtown/eaglehorn_framework | src/Eaglehorn/worker/Time/Time.php | Time.dateDiff | function dateDiff($d1, $d2)
{
$date1 = strtotime($d1);
$date2 = strtotime($d2);
$seconds = $date1 - $date2;
$weeks = floor($seconds / 604800);
$seconds -= $weeks * 604800;
$days = floor($seconds / 86400);
$seconds -= $days * 86400;
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
$months = round(($date1 - $date2) / 60 / 60 / 24 / 30);
$years = round(($date1 - $date2) / (60 * 60 * 24 * 365));
$secs_unit = (abs($seconds) == 1) ? ' Second ' : ' Seconds ';
$mins_unit = (abs($minutes) == 1) ? ' Minute ' : ' Minutes ';
$hours_unit = (abs($hours) == 1) ? ' Hour ' : ' Hours ';
$days_unit = (abs($days) == 1) ? ' Day ' : ' Days ';
$weeks_unit = (abs($weeks) == 1) ? ' Week ' : ' Weeks ';
$months_unit = (abs($months) == 1) ? ' Month ' : ' Months ';
$years_unit = (abs($years) == 1) ? ' Year ' : ' Years ';
$difference = "";
if (!empty($years))
$difference .= $years . $years_unit;
if (!empty($months))
$difference .= $months . $months_unit;
if (!empty($weeks))
$difference .= $weeks . $weeks_unit;
if (!empty($days))
$difference .= $days . $days_unit;
if (!empty($hours))
$difference .= $hours . $hours_unit;
if (!empty($minutes))
$difference .= $minutes . $mins_unit;
if (!empty($seconds))
$difference .= $seconds . $secs_unit;
return $difference;
} | php | function dateDiff($d1, $d2)
{
$date1 = strtotime($d1);
$date2 = strtotime($d2);
$seconds = $date1 - $date2;
$weeks = floor($seconds / 604800);
$seconds -= $weeks * 604800;
$days = floor($seconds / 86400);
$seconds -= $days * 86400;
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
$months = round(($date1 - $date2) / 60 / 60 / 24 / 30);
$years = round(($date1 - $date2) / (60 * 60 * 24 * 365));
$secs_unit = (abs($seconds) == 1) ? ' Second ' : ' Seconds ';
$mins_unit = (abs($minutes) == 1) ? ' Minute ' : ' Minutes ';
$hours_unit = (abs($hours) == 1) ? ' Hour ' : ' Hours ';
$days_unit = (abs($days) == 1) ? ' Day ' : ' Days ';
$weeks_unit = (abs($weeks) == 1) ? ' Week ' : ' Weeks ';
$months_unit = (abs($months) == 1) ? ' Month ' : ' Months ';
$years_unit = (abs($years) == 1) ? ' Year ' : ' Years ';
$difference = "";
if (!empty($years))
$difference .= $years . $years_unit;
if (!empty($months))
$difference .= $months . $months_unit;
if (!empty($weeks))
$difference .= $weeks . $weeks_unit;
if (!empty($days))
$difference .= $days . $days_unit;
if (!empty($hours))
$difference .= $hours . $hours_unit;
if (!empty($minutes))
$difference .= $minutes . $mins_unit;
if (!empty($seconds))
$difference .= $seconds . $secs_unit;
return $difference;
} | Time Difference
Usage: $this->time->dateDiff('2012-01-19 08:30:41','2012-01-19 06:36:42')
@param type $d1
@param type $d2
@return string | https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/worker/Time/Time.php#L87-L129 |
oliwierptak/Everon1 | src/Everon/Helper/Asserts/IsInArray.php | IsInArray.assertIsInArray | public function assertIsInArray($needle, $haystack, $message='%s must be in Array', $exception='Asserts')
{
if (isset($haystack) === false || is_array($haystack) === false || in_array($needle, $haystack) === false) {
$this->throwException($exception, $message, $needle);
}
} | php | public function assertIsInArray($needle, $haystack, $message='%s must be in Array', $exception='Asserts')
{
if (isset($haystack) === false || is_array($haystack) === false || in_array($needle, $haystack) === false) {
$this->throwException($exception, $message, $needle);
}
} | Verifies that the specified condition is in the array.
The assertion fails if the condition is not in the array or the the $haystack is not an array.
@param mixed $needle
@param mixed $haystack
@param string $message
@param string $exception
@throws \Everon\Exception\Asserts | https://github.com/oliwierptak/Everon1/blob/ac93793d1fa517a8394db5f00062f1925dc218a3/src/Everon/Helper/Asserts/IsInArray.php#L24-L29 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.wipe | protected function wipe()
{
$this->manager = null;
$this->mappingDriver = null;
$this->metadataCacheDriver = null;
$this->eventManager = null;
$this->queryCacheDriver = null;
$this->resultCacheDriver = null;
$this->namingStrategy = null;
$this->quoteStrategy = null;
$this->SQLLogger = null;
} | php | protected function wipe()
{
$this->manager = null;
$this->mappingDriver = null;
$this->metadataCacheDriver = null;
$this->eventManager = null;
$this->queryCacheDriver = null;
$this->resultCacheDriver = null;
$this->namingStrategy = null;
$this->quoteStrategy = null;
$this->SQLLogger = null;
} | {@inheritdoc} | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L113-L124 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.buildManager | protected function buildManager()
{
$config = new Configuration();
$this->setUpGeneralConfigurations($config);
$this->setUpSpecificConfigurations($config);
$eventManager = $this->getEventManager();
if ($this->getEventSubscribers() !== null) {
/* @var array $eventSubscribers */
$eventSubscribers = $this->getEventSubscribers();
foreach ($eventSubscribers as $eventSubscriber) {
$eventManager->addEventSubscriber($eventSubscriber);
}
}
$entityManager = EntityManager::create($this->getOption('connection'), $config, $eventManager);
$customMappingTypes = $this->getCustomMappingTypes();
$platform = $entityManager->getConnection()->getDatabasePlatform();
foreach ($this->getCustomTypes() as $type => $class) {
if (Type::hasType($type)) {
Type::overrideType($type, $class);
} else {
Type::addType($type, $class);
}
$platform->registerDoctrineTypeMapping(
$type,
array_key_exists($type, $customMappingTypes) ? $customMappingTypes[$type] : $type
);
}
return $entityManager;
} | php | protected function buildManager()
{
$config = new Configuration();
$this->setUpGeneralConfigurations($config);
$this->setUpSpecificConfigurations($config);
$eventManager = $this->getEventManager();
if ($this->getEventSubscribers() !== null) {
/* @var array $eventSubscribers */
$eventSubscribers = $this->getEventSubscribers();
foreach ($eventSubscribers as $eventSubscriber) {
$eventManager->addEventSubscriber($eventSubscriber);
}
}
$entityManager = EntityManager::create($this->getOption('connection'), $config, $eventManager);
$customMappingTypes = $this->getCustomMappingTypes();
$platform = $entityManager->getConnection()->getDatabasePlatform();
foreach ($this->getCustomTypes() as $type => $class) {
if (Type::hasType($type)) {
Type::overrideType($type, $class);
} else {
Type::addType($type, $class);
}
$platform->registerDoctrineTypeMapping(
$type,
array_key_exists($type, $customMappingTypes) ? $customMappingTypes[$type] : $type
);
}
return $entityManager;
} | {@inheritdoc}
@throws \Doctrine\DBAL\DBALException
@throws \Doctrine\ORM\ORMException
@throws \InvalidArgumentException
@throws \RuntimeException
@throws \UnexpectedValueException
@return EntityManager | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L137-L173 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.setUpGeneralConfigurations | protected function setUpGeneralConfigurations(Configuration $config)
{
$this->setupAnnotationMetadata();
$config->setMetadataDriverImpl($this->getMetadataMappingDriver());
$config->setProxyDir($this->getProxiesPath());
$config->setProxyNamespace($this->getProxiesNamespace());
$config->setAutoGenerateProxyClasses($this->getProxiesAutoGeneration());
if ($this->getRepositoryFactory() !== null) {
$config->setRepositoryFactory($this->getRepositoryFactory());
}
if ($this->getDefaultRepositoryClass() !== null) {
$config->setDefaultRepositoryClassName($this->getDefaultRepositoryClass());
}
$config->setMetadataCacheImpl($this->getMetadataCacheDriver());
} | php | protected function setUpGeneralConfigurations(Configuration $config)
{
$this->setupAnnotationMetadata();
$config->setMetadataDriverImpl($this->getMetadataMappingDriver());
$config->setProxyDir($this->getProxiesPath());
$config->setProxyNamespace($this->getProxiesNamespace());
$config->setAutoGenerateProxyClasses($this->getProxiesAutoGeneration());
if ($this->getRepositoryFactory() !== null) {
$config->setRepositoryFactory($this->getRepositoryFactory());
}
if ($this->getDefaultRepositoryClass() !== null) {
$config->setDefaultRepositoryClassName($this->getDefaultRepositoryClass());
}
$config->setMetadataCacheImpl($this->getMetadataCacheDriver());
} | Set up general manager configurations.
@param Configuration $config | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L180-L198 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.setUpSpecificConfigurations | protected function setUpSpecificConfigurations(Configuration $config)
{
$config->setQueryCacheImpl($this->getQueryCacheDriver());
$config->setResultCacheImpl($this->getResultCacheDriver());
$config->setHydrationCacheImpl($this->getHydratorCacheDriver());
$config->setNamingStrategy($this->getNamingStrategy());
$config->setQuoteStrategy($this->getQuoteStrategy());
if ($this->getSecondLevelCacheConfiguration() !== null) {
$config->setSecondLevelCacheEnabled(true);
$config->setSecondLevelCacheConfiguration($this->getSecondLevelCacheConfiguration());
}
$config->setSQLLogger($this->getSQLLogger());
$config->setCustomStringFunctions($this->getCustomStringFunctions());
$config->setCustomNumericFunctions($this->getCustomNumericFunctions());
$config->setCustomDatetimeFunctions($this->getCustomDateTimeFunctions());
foreach ($this->getCustomFilters() as $name => $filterClass) {
$config->addFilter($name, $filterClass);
}
} | php | protected function setUpSpecificConfigurations(Configuration $config)
{
$config->setQueryCacheImpl($this->getQueryCacheDriver());
$config->setResultCacheImpl($this->getResultCacheDriver());
$config->setHydrationCacheImpl($this->getHydratorCacheDriver());
$config->setNamingStrategy($this->getNamingStrategy());
$config->setQuoteStrategy($this->getQuoteStrategy());
if ($this->getSecondLevelCacheConfiguration() !== null) {
$config->setSecondLevelCacheEnabled(true);
$config->setSecondLevelCacheConfiguration($this->getSecondLevelCacheConfiguration());
}
$config->setSQLLogger($this->getSQLLogger());
$config->setCustomStringFunctions($this->getCustomStringFunctions());
$config->setCustomNumericFunctions($this->getCustomNumericFunctions());
$config->setCustomDatetimeFunctions($this->getCustomDateTimeFunctions());
foreach ($this->getCustomFilters() as $name => $filterClass) {
$config->addFilter($name, $filterClass);
}
} | Set up manager specific configurations.
@param Configuration $config | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L205-L227 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getRepositoryFactory | protected function getRepositoryFactory()
{
if (!array_key_exists('repository_factory', $this->options)) {
return;
}
$repositoryFactory = $this->options['repository_factory'];
if (!$repositoryFactory instanceof RepositoryFactory) {
throw new \InvalidArgumentException(sprintf(
'Invalid factory class "%s". It must be a Doctrine\ORM\Repository\RepositoryFactory.',
get_class($repositoryFactory)
));
}
return $repositoryFactory;
} | php | protected function getRepositoryFactory()
{
if (!array_key_exists('repository_factory', $this->options)) {
return;
}
$repositoryFactory = $this->options['repository_factory'];
if (!$repositoryFactory instanceof RepositoryFactory) {
throw new \InvalidArgumentException(sprintf(
'Invalid factory class "%s". It must be a Doctrine\ORM\Repository\RepositoryFactory.',
get_class($repositoryFactory)
));
}
return $repositoryFactory;
} | {@inheritdoc}
@throws \InvalidArgumentException
@return RepositoryFactory|null | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L264-L280 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getQueryCacheDriver | public function getQueryCacheDriver()
{
if (!$this->queryCacheDriver instanceof CacheProvider) {
$this->queryCacheDriver = $this->getCacheDriver(
(string) $this->getOption('query_cache_namespace'),
$this->getOption('query_cache_driver')
);
}
return $this->queryCacheDriver;
} | php | public function getQueryCacheDriver()
{
if (!$this->queryCacheDriver instanceof CacheProvider) {
$this->queryCacheDriver = $this->getCacheDriver(
(string) $this->getOption('query_cache_namespace'),
$this->getOption('query_cache_driver')
);
}
return $this->queryCacheDriver;
} | Retrieve query cache driver.
@throws \InvalidArgumentException
@return CacheProvider | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L289-L299 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getResultCacheDriver | public function getResultCacheDriver()
{
if (!$this->resultCacheDriver instanceof CacheProvider) {
$this->resultCacheDriver = $this->getCacheDriver(
(string) $this->getOption('result_cache_namespace'),
$this->getOption('result_cache_driver')
);
}
return $this->resultCacheDriver;
} | php | public function getResultCacheDriver()
{
if (!$this->resultCacheDriver instanceof CacheProvider) {
$this->resultCacheDriver = $this->getCacheDriver(
(string) $this->getOption('result_cache_namespace'),
$this->getOption('result_cache_driver')
);
}
return $this->resultCacheDriver;
} | Retrieve result cache driver.
@throws \InvalidArgumentException
@return CacheProvider | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L318-L328 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getHydratorCacheDriver | public function getHydratorCacheDriver()
{
if (!$this->hydratorCacheDriver instanceof CacheProvider) {
$this->hydratorCacheDriver = $this->getCacheDriver(
(string) $this->getOption('hydrator_cache_namespace'),
$this->getOption('hydrator_cache_driver')
);
}
return $this->hydratorCacheDriver;
} | php | public function getHydratorCacheDriver()
{
if (!$this->hydratorCacheDriver instanceof CacheProvider) {
$this->hydratorCacheDriver = $this->getCacheDriver(
(string) $this->getOption('hydrator_cache_namespace'),
$this->getOption('hydrator_cache_driver')
);
}
return $this->hydratorCacheDriver;
} | Retrieve hydrator cache driver.
@throws \InvalidArgumentException
@return CacheProvider | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L347-L357 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getCacheDriver | protected function getCacheDriver($cacheNamespace, CacheProvider $cacheDriver = null)
{
if (!$cacheDriver instanceof CacheProvider) {
$cacheDriver = clone $this->getMetadataCacheDriver();
$cacheDriver->setNamespace($cacheNamespace);
}
if ($cacheDriver->getNamespace() === '') {
$cacheDriver->setNamespace($cacheNamespace);
}
return $cacheDriver;
} | php | protected function getCacheDriver($cacheNamespace, CacheProvider $cacheDriver = null)
{
if (!$cacheDriver instanceof CacheProvider) {
$cacheDriver = clone $this->getMetadataCacheDriver();
$cacheDriver->setNamespace($cacheNamespace);
}
if ($cacheDriver->getNamespace() === '') {
$cacheDriver->setNamespace($cacheNamespace);
}
return $cacheDriver;
} | Get cache driver.
@param string $cacheNamespace
@param CacheProvider|null $cacheDriver
@return CacheProvider | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L377-L389 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getNamingStrategy | protected function getNamingStrategy()
{
if (!$this->namingStrategy instanceof NamingStrategy) {
$namingStrategy = $this->getOption('naming_strategy');
if (!$namingStrategy instanceof NamingStrategy) {
$namingStrategy = new UnderscoreNamingStrategy(CASE_LOWER);
}
$this->namingStrategy = $namingStrategy;
}
return $this->namingStrategy;
} | php | protected function getNamingStrategy()
{
if (!$this->namingStrategy instanceof NamingStrategy) {
$namingStrategy = $this->getOption('naming_strategy');
if (!$namingStrategy instanceof NamingStrategy) {
$namingStrategy = new UnderscoreNamingStrategy(CASE_LOWER);
}
$this->namingStrategy = $namingStrategy;
}
return $this->namingStrategy;
} | Retrieve naming strategy.
@return NamingStrategy | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L396-L409 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getQuoteStrategy | protected function getQuoteStrategy()
{
if (!$this->quoteStrategy instanceof QuoteStrategy) {
$quoteStrategy = $this->getOption('quote_strategy');
if (!$quoteStrategy instanceof QuoteStrategy) {
$quoteStrategy = new DefaultQuoteStrategy;
}
$this->quoteStrategy = $quoteStrategy;
}
return $this->quoteStrategy;
} | php | protected function getQuoteStrategy()
{
if (!$this->quoteStrategy instanceof QuoteStrategy) {
$quoteStrategy = $this->getOption('quote_strategy');
if (!$quoteStrategy instanceof QuoteStrategy) {
$quoteStrategy = new DefaultQuoteStrategy;
}
$this->quoteStrategy = $quoteStrategy;
}
return $this->quoteStrategy;
} | Retrieve quote strategy.
@throws \InvalidArgumentException
@return QuoteStrategy | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L418-L431 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getSecondLevelCacheConfiguration | protected function getSecondLevelCacheConfiguration()
{
if (!$this->secondCacheConfig instanceof CacheConfiguration) {
$secondCacheConfig = $this->getOption('second_level_cache_configuration');
if ($secondCacheConfig instanceof CacheConfiguration) {
$this->secondCacheConfig = $secondCacheConfig;
}
}
return $this->secondCacheConfig;
} | php | protected function getSecondLevelCacheConfiguration()
{
if (!$this->secondCacheConfig instanceof CacheConfiguration) {
$secondCacheConfig = $this->getOption('second_level_cache_configuration');
if ($secondCacheConfig instanceof CacheConfiguration) {
$this->secondCacheConfig = $secondCacheConfig;
}
}
return $this->secondCacheConfig;
} | Retrieve second level cache configuration.
@return CacheConfiguration|null | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L438-L449 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getSQLLogger | protected function getSQLLogger()
{
if (!$this->SQLLogger instanceof SQLLogger) {
$sqlLogger = $this->getOption('sql_logger');
if ($sqlLogger instanceof SQLLogger) {
$this->SQLLogger = $sqlLogger;
}
}
return $this->SQLLogger;
} | php | protected function getSQLLogger()
{
if (!$this->SQLLogger instanceof SQLLogger) {
$sqlLogger = $this->getOption('sql_logger');
if ($sqlLogger instanceof SQLLogger) {
$this->SQLLogger = $sqlLogger;
}
}
return $this->SQLLogger;
} | Retrieve SQL logger.
@return SQLLogger|null | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L456-L467 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getCustomStringFunctions | protected function getCustomStringFunctions()
{
$functions = (array) $this->getOption('custom_string_functions');
return array_filter(
$functions,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | php | protected function getCustomStringFunctions()
{
$functions = (array) $this->getOption('custom_string_functions');
return array_filter(
$functions,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | Retrieve custom DQL string functions.
@return array | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L474-L485 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getCustomNumericFunctions | protected function getCustomNumericFunctions()
{
$functions = (array) $this->getOption('custom_numeric_functions');
return array_filter(
$functions,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | php | protected function getCustomNumericFunctions()
{
$functions = (array) $this->getOption('custom_numeric_functions');
return array_filter(
$functions,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | Retrieve custom DQL numeric functions.
@return array | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L492-L503 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getCustomDateTimeFunctions | protected function getCustomDateTimeFunctions()
{
$functions = (array) $this->getOption('custom_datetime_functions');
return array_filter(
$functions,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | php | protected function getCustomDateTimeFunctions()
{
$functions = (array) $this->getOption('custom_datetime_functions');
return array_filter(
$functions,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | Retrieve custom DQL date time functions.
@return array | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L510-L521 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getCustomTypes | protected function getCustomTypes()
{
$types = (array) $this->getOption('custom_types');
return array_filter(
$types,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | php | protected function getCustomTypes()
{
$types = (array) $this->getOption('custom_types');
return array_filter(
$types,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | Retrieve custom DBAL types.
@return array | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L528-L539 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getCustomMappingTypes | protected function getCustomMappingTypes()
{
$mappingTypes = (array) $this->getOption('custom_mapping_types');
return array_filter(
$mappingTypes,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | php | protected function getCustomMappingTypes()
{
$mappingTypes = (array) $this->getOption('custom_mapping_types');
return array_filter(
$mappingTypes,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | Retrieve custom DBAL mapping types.
@return array | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L546-L557 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getCustomFilters | protected function getCustomFilters()
{
$filters = (array) $this->getOption('custom_filters');
return array_filter(
$filters,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | php | protected function getCustomFilters()
{
$filters = (array) $this->getOption('custom_filters');
return array_filter(
$filters,
function ($name) {
return is_string($name);
},
ARRAY_FILTER_USE_KEY
);
} | Get custom registered filters.
@return array | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L564-L575 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getConsoleCommands | public function getConsoleCommands()
{
$commands = [
// DBAL
new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
// ORM
new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(),
new \Doctrine\ORM\Tools\Console\Command\InfoCommand(),
];
if (Version::compare('2.5') <= 0) {
$commands[] = new \Doctrine\ORM\Tools\Console\Command\MappingDescribeCommand();
}
$helperSet = $this->getConsoleHelperSet();
$commandPrefix = (string) $this->getName();
$commands = array_map(
function (Command $command) use ($helperSet, $commandPrefix) {
if ($commandPrefix !== '') {
$commandNames = array_map(
function ($commandName) use ($commandPrefix) {
return preg_replace('/^(dbal|orm):/', '$1:' . $commandPrefix . ':', $commandName);
},
array_merge([$command->getName()], $command->getAliases())
);
$command->setName(array_shift($commandNames));
$command->setAliases($commandNames);
}
$command->setHelperSet($helperSet);
return $command;
},
$commands
);
return $commands;
} | php | public function getConsoleCommands()
{
$commands = [
// DBAL
new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
// ORM
new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(),
new \Doctrine\ORM\Tools\Console\Command\InfoCommand(),
];
if (Version::compare('2.5') <= 0) {
$commands[] = new \Doctrine\ORM\Tools\Console\Command\MappingDescribeCommand();
}
$helperSet = $this->getConsoleHelperSet();
$commandPrefix = (string) $this->getName();
$commands = array_map(
function (Command $command) use ($helperSet, $commandPrefix) {
if ($commandPrefix !== '') {
$commandNames = array_map(
function ($commandName) use ($commandPrefix) {
return preg_replace('/^(dbal|orm):/', '$1:' . $commandPrefix . ':', $commandName);
},
array_merge([$command->getName()], $command->getAliases())
);
$command->setName(array_shift($commandNames));
$command->setAliases($commandNames);
}
$command->setHelperSet($helperSet);
return $command;
},
$commands
);
return $commands;
} | {@inheritdoc}
@throws \Doctrine\DBAL\DBALException
@throws \Doctrine\ORM\ORMException
@throws \InvalidArgumentException
@throws \RuntimeException
@throws \Symfony\Component\Console\Exception\InvalidArgumentException
@throws \Symfony\Component\Console\Exception\LogicException
@throws \UnexpectedValueException
@return Command[] | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L590-L644 |
juliangut/doctrine-manager-builder | src/RelationalBuilder.php | RelationalBuilder.getConsoleHelperSet | protected function getConsoleHelperSet()
{
/* @var EntityManager $entityManager */
$entityManager = $this->getManager();
return new HelperSet([
'db' => new ConnectionHelper($entityManager->getConnection()),
'em' => new EntityManagerHelper($entityManager),
]);
} | php | protected function getConsoleHelperSet()
{
/* @var EntityManager $entityManager */
$entityManager = $this->getManager();
return new HelperSet([
'db' => new ConnectionHelper($entityManager->getConnection()),
'em' => new EntityManagerHelper($entityManager),
]);
} | Get console helper set.
@return \Symfony\Component\Console\Helper\HelperSet | https://github.com/juliangut/doctrine-manager-builder/blob/9c63bc689e4084f06be4d119f2c56f6040453d0e/src/RelationalBuilder.php#L651-L660 |
Phauthentic/password-hashers | src/AbstractPasswordHasher.php | AbstractPasswordHasher.setSalt | public function setSalt(string $salt, string $position = self::SALT_AFTER): self
{
$this->checkSaltPositionArgument($position);
$this->salt = $salt;
$this->saltPosition = $position;
return $this;
} | php | public function setSalt(string $salt, string $position = self::SALT_AFTER): self
{
$this->checkSaltPositionArgument($position);
$this->salt = $salt;
$this->saltPosition = $position;
return $this;
} | Sets the salt if any was used
@return $this | https://github.com/Phauthentic/password-hashers/blob/c0679d51c941d8808ae143a20e63daab2d4388ec/src/AbstractPasswordHasher.php#L46-L53 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.