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
|
---|---|---|---|---|---|---|---|
BenGorFile/FileBundle | src/BenGorFile/FileBundle/Form/Type/FileType.php | FileType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('bengor_file', BaseFileType::class, [
'required' => $options['required'],
'label' => $options['label'],
'attr' => $options['attr'],
'mapped' => $options['mapped'],
]);
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('bengor_file', BaseFileType::class, [
'required' => $options['required'],
'label' => $options['label'],
'attr' => $options['attr'],
'mapped' => $options['mapped'],
]);
} | {@inheritdoc} | https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/Form/Type/FileType.php#L32-L40 |
BenGorFile/FileBundle | src/BenGorFile/FileBundle/Form/Type/FileType.php | FileType.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => UploadFileCommand::class,
'error_bubbling' => false,
'label' => false,
'required' => false,
'mapped' => false,
'empty_data' => function (FormInterface $form) {
return $this->emptyData($form);
},
]);
} | php | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => UploadFileCommand::class,
'error_bubbling' => false,
'label' => false,
'required' => false,
'mapped' => false,
'empty_data' => function (FormInterface $form) {
return $this->emptyData($form);
},
]);
} | {@inheritdoc} | https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/Form/Type/FileType.php#L45-L57 |
BenGorFile/FileBundle | src/BenGorFile/FileBundle/Form/Type/FileType.php | FileType.emptyData | public function emptyData(FormInterface $form)
{
$file = $form->get('bengor_file')->getData();
if (null === $file) {
return;
}
return new UploadFileCommand(
$file->getClientOriginalName(),
file_get_contents($file->getPathname()),
$file->getMimeType()
);
} | php | public function emptyData(FormInterface $form)
{
$file = $form->get('bengor_file')->getData();
if (null === $file) {
return;
}
return new UploadFileCommand(
$file->getClientOriginalName(),
file_get_contents($file->getPathname()),
$file->getMimeType()
);
} | Method that encapsulates all the logic of build empty data.
It returns an instance of data class object.
@param FormInterface $form The form
@return UploadFileCommand|null | https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/Form/Type/FileType.php#L75-L87 |
Synapse-Cmf/synapse-cmf | src/Synapse/Page/Bundle/Form/PageMenu/PageMenuType.php | PageMenuType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('data', CollectionType::class, array(
'entry_type' => PageMenuItemType::class,
'allow_add' => true,
'allow_delete' => true,
'attr' => [
'class' => 'synapse-page-menu-data',
],
))
;
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('data', CollectionType::class, array(
'entry_type' => PageMenuItemType::class,
'allow_add' => true,
'allow_delete' => true,
'attr' => [
'class' => 'synapse-page-menu-data',
],
))
;
} | Menu component form prototype definition.
@see FormInterface::buildForm() | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Page/Bundle/Form/PageMenu/PageMenuType.php#L30-L42 |
issei-m/spike-php | src/Util/DateTimeUtil.php | DateTimeUtil.createDateTimeByUnixTime | public function createDateTimeByUnixTime($unixTime)
{
$dateTime = new \DateTime('@' . $unixTime);
$dateTime->setTimezone($this->specifiedTimeZone);
return $dateTime;
} | php | public function createDateTimeByUnixTime($unixTime)
{
$dateTime = new \DateTime('@' . $unixTime);
$dateTime->setTimezone($this->specifiedTimeZone);
return $dateTime;
} | Returns the created DateTime object specified the timezone.
@param $unixTime
@return \DateTime | https://github.com/issei-m/spike-php/blob/9205b5047a1132bcdca6731feac02fe3d5dc1023/src/Util/DateTimeUtil.php#L26-L32 |
PlatoCreative/silverstripe-sections | code/sections/ImageBannerSection.php | ImageBannerSection.getCMSFields | public function getCMSFields()
{
$linksGridConfig = GridFieldConfig_RelationEditor::create();
if ($this->Links()->Count() > 0) {
$linksGridConfig->addComponent(new GridFieldOrderableRows());
}
$fields = parent::getCMSFields();
$fields->addFieldsToTab(
"Root.Main",
array(
TextareaField::create(
'Title'
)->setRows(1),
HTMLEditorField::create(
'Content'
),
SortableUploadField::create(
'Images',
'Current Image(s)'
),
GridField::create(
'Links',
'Links',
$this->Links(),
$linksGridConfig
)
)
);
$this->extend('updateCMSFields', $fields);
return $fields;
} | php | public function getCMSFields()
{
$linksGridConfig = GridFieldConfig_RelationEditor::create();
if ($this->Links()->Count() > 0) {
$linksGridConfig->addComponent(new GridFieldOrderableRows());
}
$fields = parent::getCMSFields();
$fields->addFieldsToTab(
"Root.Main",
array(
TextareaField::create(
'Title'
)->setRows(1),
HTMLEditorField::create(
'Content'
),
SortableUploadField::create(
'Images',
'Current Image(s)'
),
GridField::create(
'Links',
'Links',
$this->Links(),
$linksGridConfig
)
)
);
$this->extend('updateCMSFields', $fields);
return $fields;
} | CMS Fields
@return array | https://github.com/PlatoCreative/silverstripe-sections/blob/54c96146ea8cc625b00ee009753539658f10d01a/code/sections/ImageBannerSection.php#L49-L82 |
limingxinleo/phalcon-utils | src/Ajax.php | Ajax.ajaxResponse | public static function ajaxResponse($status = 1, $data = [], $message = '')
{
$out = [
'status' => $status,
'message' => $message,
'data' => $data,
'timestamp' => time()
];
echo json_encode($out);
exit;
} | php | public static function ajaxResponse($status = 1, $data = [], $message = '')
{
$out = [
'status' => $status,
'message' => $message,
'data' => $data,
'timestamp' => time()
];
echo json_encode($out);
exit;
} | [ajaxResponse 返回特定格式的json]
@author limx
@param int $status 状态码
@param array $data 数据包
@param string $message 错误信息
@return JsonResponse | https://github.com/limingxinleo/phalcon-utils/blob/6581a8982a1244908de9e5197dc9284e3949ded7/src/Ajax.php#L20-L31 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceController.php | HCServiceController.optimize | public function optimize(stdClass $data)
{
$data->controllerName = $data->serviceName . 'Controller';
// creating name space from service URL
$data->controllerNamespace = str_replace('/', '\\', $data->directory . 'app\http\controllers\\' . str_replace('-', '', $data->serviceURL));
$data->controllerNamespace = array_filter(explode('\\', $data->controllerNamespace));
array_pop($data->controllerNamespace);
$data->controllerNamespace = implode('\\', $data->controllerNamespace);
$data->controllerNamespace = str_replace('-', '', $data->controllerNamespace);
$routesNameSpace = str_replace('/', '\\\\', $this->createItemDirectoryPath(str_replace('-', '', $data->serviceURL)));
if( $routesNameSpace == "" )
$data->controllerNameForRoutes = $data->controllerName;
else
$data->controllerNameForRoutes = $routesNameSpace . '\\\\' . $data->controllerName;
// creating controller directory
$data->controllerDestination = $this->createItemDirectoryPath($data->rootDirectory . 'app/http/controllers/' . str_replace('-', '', $data->serviceURL));
return $data;
} | php | public function optimize(stdClass $data)
{
$data->controllerName = $data->serviceName . 'Controller';
// creating name space from service URL
$data->controllerNamespace = str_replace('/', '\\', $data->directory . 'app\http\controllers\\' . str_replace('-', '', $data->serviceURL));
$data->controllerNamespace = array_filter(explode('\\', $data->controllerNamespace));
array_pop($data->controllerNamespace);
$data->controllerNamespace = implode('\\', $data->controllerNamespace);
$data->controllerNamespace = str_replace('-', '', $data->controllerNamespace);
$routesNameSpace = str_replace('/', '\\\\', $this->createItemDirectoryPath(str_replace('-', '', $data->serviceURL)));
if( $routesNameSpace == "" )
$data->controllerNameForRoutes = $data->controllerName;
else
$data->controllerNameForRoutes = $routesNameSpace . '\\\\' . $data->controllerName;
// creating controller directory
$data->controllerDestination = $this->createItemDirectoryPath($data->rootDirectory . 'app/http/controllers/' . str_replace('-', '', $data->serviceURL));
return $data;
} | Creating models
@param $data
@internal param $item
@internal param $modelData
@return stdClass | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceController.php#L23-L46 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceController.php | HCServiceController.createItemDirectoryPath | private function createItemDirectoryPath(string $item)
{
$item = array_filter(explode('/', $item));
array_pop($item);
$item = implode('/', $item);
return $item;
} | php | private function createItemDirectoryPath(string $item)
{
$item = array_filter(explode('/', $item));
array_pop($item);
$item = implode('/', $item);
return $item;
} | Creating path
@param $item
@return array|string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceController.php#L53-L60 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceController.php | HCServiceController.createMultiLanguageController | private function createMultiLanguageController(stdClass $data)
{
$this->createFileFromTemplate([
"destination" => $data->controllerDestination,
"templateDestination" => __DIR__ . '/../templates/service/controller/multiLanguage.hctpl',
"content" => [
"namespace" => $data->controllerNamespace,
"controllerName" => $data->controllerName,
"acl_prefix" => $data->aclPrefix,
"serviceURL" => $data->serviceURL,
"translationsLocation" => $data->translationsLocation,
"serviceNameDotted" => $this->stringWithDash($data->translationFilePrefix),
"controllerNameDotted" => $data->serviceRouteName,
"adminListHeader" => $this->getAdminListHeader($data),
"formValidationName" => $data->formValidationName,
"translationsFormValidationName" => $data->formTranslationsValidationName,
"functions" => replaceBrackets(file_get_contents(__DIR__ . '/../templates/service/controller/multilanguage/functions.hctpl'),
[
"modelName" => $data->mainModel->modelName,
"modelNameSpace" => $data->modelNamespace,
]),
"inputData" => $this->getInputData($data),
"useFiles" => $this->getUseFiles($data, true),
"mainModelName" => $data->mainModel->modelName,
"searchableFields" => $this->getSearchableFields($data),
"searchableFieldsTranslations" => $this->getSearchableFields($data, true),
],
]);
return $data->controllerDestination;
} | php | private function createMultiLanguageController(stdClass $data)
{
$this->createFileFromTemplate([
"destination" => $data->controllerDestination,
"templateDestination" => __DIR__ . '/../templates/service/controller/multiLanguage.hctpl',
"content" => [
"namespace" => $data->controllerNamespace,
"controllerName" => $data->controllerName,
"acl_prefix" => $data->aclPrefix,
"serviceURL" => $data->serviceURL,
"translationsLocation" => $data->translationsLocation,
"serviceNameDotted" => $this->stringWithDash($data->translationFilePrefix),
"controllerNameDotted" => $data->serviceRouteName,
"adminListHeader" => $this->getAdminListHeader($data),
"formValidationName" => $data->formValidationName,
"translationsFormValidationName" => $data->formTranslationsValidationName,
"functions" => replaceBrackets(file_get_contents(__DIR__ . '/../templates/service/controller/multilanguage/functions.hctpl'),
[
"modelName" => $data->mainModel->modelName,
"modelNameSpace" => $data->modelNamespace,
]),
"inputData" => $this->getInputData($data),
"useFiles" => $this->getUseFiles($data, true),
"mainModelName" => $data->mainModel->modelName,
"searchableFields" => $this->getSearchableFields($data),
"searchableFieldsTranslations" => $this->getSearchableFields($data, true),
],
]);
return $data->controllerDestination;
} | Creating multi language controller
@param stdClass $data | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceController.php#L75-L105 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceController.php | HCServiceController.getAdminListHeader | private function getAdminListHeader(stdClass $data)
{
$output = '';
$model = $data->mainModel;
//getting parameters which are not multilanguage
$output .= $this->gatherHeaders($model, array_merge($this->getAutoFill(), ['id']), $data->translationsLocation, false);
//getting parameters which are not multilanguage
if( isset($model->multiLanguage) )
$output .= $this->gatherHeaders($model->multiLanguage, array_merge($this->getAutoFill(), ['id', 'language_code', 'record_id']), $data->translationsLocation, true);
return $output;
} | php | private function getAdminListHeader(stdClass $data)
{
$output = '';
$model = $data->mainModel;
//getting parameters which are not multilanguage
$output .= $this->gatherHeaders($model, array_merge($this->getAutoFill(), ['id']), $data->translationsLocation, false);
//getting parameters which are not multilanguage
if( isset($model->multiLanguage) )
$output .= $this->gatherHeaders($model->multiLanguage, array_merge($this->getAutoFill(), ['id', 'language_code', 'record_id']), $data->translationsLocation, true);
return $output;
} | Get list header from model data
@param $data
@return string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceController.php#L147-L160 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceController.php | HCServiceController.getInputData | private function getInputData(stdClass $data)
{
$output = '';
$skip = array_merge($this->getAutoFill(), ['id']);
if( ! empty($data->database) ) {
if( isset($data->multiLanguage) )
$path = '/templates/service/controller/multilanguage/input.data.hctpl';
else
$path = '/templates/service/controller/basic/input.data.hctpl';
$tpl = file_get_contents(__DIR__ . '/..' . $path);
foreach ( $data->database as $tableName => $model )
if( array_key_exists('columns', $model) && ! empty($model->columns) && isset($model->default) )
foreach ( $model->columns as $column ) {
if( in_array($column->Field, $skip) )
continue;
$line = str_replace('{key}', $column->Field, $tpl);
$output .= $line;
}
}
return $output;
} | php | private function getInputData(stdClass $data)
{
$output = '';
$skip = array_merge($this->getAutoFill(), ['id']);
if( ! empty($data->database) ) {
if( isset($data->multiLanguage) )
$path = '/templates/service/controller/multilanguage/input.data.hctpl';
else
$path = '/templates/service/controller/basic/input.data.hctpl';
$tpl = file_get_contents(__DIR__ . '/..' . $path);
foreach ( $data->database as $tableName => $model )
if( array_key_exists('columns', $model) && ! empty($model->columns) && isset($model->default) )
foreach ( $model->columns as $column ) {
if( in_array($column->Field, $skip) )
continue;
$line = str_replace('{key}', $column->Field, $tpl);
$output .= $line;
}
}
return $output;
} | Get input keys from model data
@param $data
@return string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceController.php#L191-L217 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceController.php | HCServiceController.getUseFiles | private function getUseFiles(stdClass $data, bool $multiLanguage = false)
{
$output = '';
$list = [];
$list[] = [
"nameSpace" => $data->modelNamespace,
"name" => $data->mainModel->modelName,
];
if( $multiLanguage )
$list[] = [
"nameSpace" => $data->modelNamespace,
"name" => $data->mainModel->modelName . 'Translations',
];
$list[] = [
"nameSpace" => $data->formValidationNameSpace,
"name" => $data->formValidationName,
];
if( isset($data->mainModel->multiLanguage) ) {
$list[] = [
"nameSpace" => $data->formValidationNameSpace,
"name" => $data->formTranslationsValidationName,
];
}
foreach ( $list as $key => $value )
$output .= "\r\n" . 'use ' . $value['nameSpace'] . '\\' . $value['name'] . ';';
return $output;
} | php | private function getUseFiles(stdClass $data, bool $multiLanguage = false)
{
$output = '';
$list = [];
$list[] = [
"nameSpace" => $data->modelNamespace,
"name" => $data->mainModel->modelName,
];
if( $multiLanguage )
$list[] = [
"nameSpace" => $data->modelNamespace,
"name" => $data->mainModel->modelName . 'Translations',
];
$list[] = [
"nameSpace" => $data->formValidationNameSpace,
"name" => $data->formValidationName,
];
if( isset($data->mainModel->multiLanguage) ) {
$list[] = [
"nameSpace" => $data->formValidationNameSpace,
"name" => $data->formTranslationsValidationName,
];
}
foreach ( $list as $key => $value )
$output .= "\r\n" . 'use ' . $value['nameSpace'] . '\\' . $value['name'] . ';';
return $output;
} | get use files
@param stdClass $data
@param bool $multiLanguage
@return string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceController.php#L226-L259 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceController.php | HCServiceController.getSearchableFields | private function getSearchableFields(stdClass $data, bool $multiLanguage = false)
{
$output = '';
$model = $data->mainModel;
$whereTpl = file_get_contents(__DIR__ . '/../templates/shared/where.hctpl');
$orWhereTpl = file_get_contents(__DIR__ . '/../templates/shared/or.where.hctpl');
$skip = array_merge($this->getAutoFill(), ['id']);
if( $multiLanguage ) {
if( array_key_exists('multiLanguage', $model) && ! empty($model->multiLanguage) )
if( array_key_exists('columns', $model->multiLanguage) && ! empty($model->multiLanguage->columns) )
foreach ( $model->multiLanguage->columns as $index => $column ) {
if( in_array($column->Field, $skip) )
continue;
if( $output == '' )
$output .= str_replace('{key}', $column->Field, $whereTpl);
else
$output .= str_replace('{key}', $column->Field, $orWhereTpl);
}
} else
if( array_key_exists('columns', $model) && ! empty($model->columns) ) {
foreach ( $model->columns as $index => $column ) {
if( in_array($column->Field, $skip) )
continue;
if( $output == '' )
$output .= str_replace('{key}', $column->Field, $whereTpl);
else
$output .= str_replace('{key}', $column->Field, $orWhereTpl);
}
}
return $output;
} | php | private function getSearchableFields(stdClass $data, bool $multiLanguage = false)
{
$output = '';
$model = $data->mainModel;
$whereTpl = file_get_contents(__DIR__ . '/../templates/shared/where.hctpl');
$orWhereTpl = file_get_contents(__DIR__ . '/../templates/shared/or.where.hctpl');
$skip = array_merge($this->getAutoFill(), ['id']);
if( $multiLanguage ) {
if( array_key_exists('multiLanguage', $model) && ! empty($model->multiLanguage) )
if( array_key_exists('columns', $model->multiLanguage) && ! empty($model->multiLanguage->columns) )
foreach ( $model->multiLanguage->columns as $index => $column ) {
if( in_array($column->Field, $skip) )
continue;
if( $output == '' )
$output .= str_replace('{key}', $column->Field, $whereTpl);
else
$output .= str_replace('{key}', $column->Field, $orWhereTpl);
}
} else
if( array_key_exists('columns', $model) && ! empty($model->columns) ) {
foreach ( $model->columns as $index => $column ) {
if( in_array($column->Field, $skip) )
continue;
if( $output == '' )
$output .= str_replace('{key}', $column->Field, $whereTpl);
else
$output .= str_replace('{key}', $column->Field, $orWhereTpl);
}
}
return $output;
} | Get searchable fields from model data
@param stdClass $data
@param bool $multiLanguage
@return string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceController.php#L268-L309 |
brainexe/core | src/Console/SwaggerDumpCommand.php | SwaggerDumpCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$applicationName = $this->getParameter('application.name');
$routes = $this->routes->all();
$resources = $this->getResources($routes);
$url = parse_url($this->getParameter('application.url'));
$formatted = [
'swagger' => '2.0',
'info' => [
'title' => $applicationName,
'description' => sprintf('%s API', $applicationName),
'version' => '1.0.0'
],
'consumes' => ['application/json'],
'produces' => ['application/json', 'text/html'],
'host' => $url['host'],
'schemes' => [$url['scheme']],
'securityDefinitions' => [
'token' => [
'type' => 'apiKey',
'description' => 'Given API Token',
'name' => 'Token',
'in' => 'Header'
]
],
'security' => [
'token' => [
'all'
]
],
'paths' => $resources,
];
$dumper = new Dumper();
$output->writeln($dumper->dump($formatted, 4));
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$applicationName = $this->getParameter('application.name');
$routes = $this->routes->all();
$resources = $this->getResources($routes);
$url = parse_url($this->getParameter('application.url'));
$formatted = [
'swagger' => '2.0',
'info' => [
'title' => $applicationName,
'description' => sprintf('%s API', $applicationName),
'version' => '1.0.0'
],
'consumes' => ['application/json'],
'produces' => ['application/json', 'text/html'],
'host' => $url['host'],
'schemes' => [$url['scheme']],
'securityDefinitions' => [
'token' => [
'type' => 'apiKey',
'description' => 'Given API Token',
'name' => 'Token',
'in' => 'Header'
]
],
'security' => [
'token' => [
'all'
]
],
'paths' => $resources,
];
$dumper = new Dumper();
$output->writeln($dumper->dump($formatted, 4));
} | {@inheritdoc} | https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/Console/SwaggerDumpCommand.php#L52-L90 |
codex-project/addon-auth | src/Socialite/BitbucketProvider.php | BitbucketProvider.getUserByToken | protected function getUserByToken($token)
{
$response = $this->getHttpClient()->get('https://api.bitbucket.org/2.0/user', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
],
]);
$user = json_decode($response->getBody(), true);
$user[ 'email' ] = $this->getEmailByToken($token);
$user[ 'groups' ] = $this->getGroupsByToken($token);
return $user;
} | php | protected function getUserByToken($token)
{
$response = $this->getHttpClient()->get('https://api.bitbucket.org/2.0/user', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
],
]);
$user = json_decode($response->getBody(), true);
$user[ 'email' ] = $this->getEmailByToken($token);
$user[ 'groups' ] = $this->getGroupsByToken($token);
return $user;
} | {@inheritdoc} | https://github.com/codex-project/addon-auth/blob/3849a6f915cbf3e3fca7a78113ec0377dea1ba48/src/Socialite/BitbucketProvider.php#L59-L75 |
evispa/TranslationEditorBundle | Form/PropertyAccessor.php | PropertyAccessor.getPropertyPath | private function getPropertyPath($propertyPath)
{
if (!isset($this->propertyPaths[$propertyPath])) {
$this->propertyPaths[$propertyPath] = new \Symfony\Component\Form\Util\PropertyPath($propertyPath);
}
return $this->propertyPaths[$propertyPath];
} | php | private function getPropertyPath($propertyPath)
{
if (!isset($this->propertyPaths[$propertyPath])) {
$this->propertyPaths[$propertyPath] = new \Symfony\Component\Form\Util\PropertyPath($propertyPath);
}
return $this->propertyPaths[$propertyPath];
} | Get property path object.
@param string $propertyPath Property path string.
@return \Symfony\Component\Form\Util\PropertyPath | https://github.com/evispa/TranslationEditorBundle/blob/312040605c331fc2520f5d042bc00b05608554b5/Form/PropertyAccessor.php#L32-L38 |
querformat/contao-layout-sections-extender | src/layout-sections-extender/dca/tl_article.php | tl_article_qf.addCustomLayoutSectionsHook | public function addCustomLayoutSectionsHook(DataContainer $dc)
{
$arrSections = $this->getActiveLayoutSections($dc);
if (isset($GLOBALS['TL_HOOKS']['addLayoutSections']) && is_array($GLOBALS['TL_HOOKS']['addLayoutSections'])) {
foreach ($GLOBALS['TL_HOOKS']['addLayoutSections'] as $arrCustomSections) {
if (is_array($arrCustomSections) && count($arrCustomSections) > 0) {
foreach ($arrCustomSections as $k => $v) {
if (empty($v))
$arrCustomSections[$k] = $k;
}
$arrSections = array_merge($arrSections, $arrCustomSections);
}
}
}
return $arrSections;
} | php | public function addCustomLayoutSectionsHook(DataContainer $dc)
{
$arrSections = $this->getActiveLayoutSections($dc);
if (isset($GLOBALS['TL_HOOKS']['addLayoutSections']) && is_array($GLOBALS['TL_HOOKS']['addLayoutSections'])) {
foreach ($GLOBALS['TL_HOOKS']['addLayoutSections'] as $arrCustomSections) {
if (is_array($arrCustomSections) && count($arrCustomSections) > 0) {
foreach ($arrCustomSections as $k => $v) {
if (empty($v))
$arrCustomSections[$k] = $k;
}
$arrSections = array_merge($arrSections, $arrCustomSections);
}
}
}
return $arrSections;
} | Costum Column Hack
@param DataContainer $dc
@return array | https://github.com/querformat/contao-layout-sections-extender/blob/db75bf7d6e6e58342fdbb4d1e0ddc52b86fc7349/src/layout-sections-extender/dca/tl_article.php#L25-L40 |
ideil/laravel-generic-file | src/GenericFile.php | GenericFile.saveModelData | protected function saveModelData(Model $model, \Ideil\GenericFile\Interpolator\InterpolatorResult $input)
{
// prepare data to fill model
$model_map = $model->getFileAssignMap();
$model_fields = [];
foreach ($input->getData() as $field => $value) {
$model_fields[isset($model_map[$field]) ? $model_map[$field] : $field] = $value;
}
// not save, just fill data
$model->fill($model_fields);
return $model;
} | php | protected function saveModelData(Model $model, \Ideil\GenericFile\Interpolator\InterpolatorResult $input)
{
// prepare data to fill model
$model_map = $model->getFileAssignMap();
$model_fields = [];
foreach ($input->getData() as $field => $value) {
$model_fields[isset($model_map[$field]) ? $model_map[$field] : $field] = $value;
}
// not save, just fill data
$model->fill($model_fields);
return $model;
} | Save file attributes required for interpolation to model.
@param string|Illuminate\Database\Eloquent\Model $model
@param Ideil\LaravelFileOre\Interpolator\InterpolatorResult $input
@return Illuminate\Database\Eloquent\Model | https://github.com/ideil/laravel-generic-file/blob/3eaeadf06dfb295c391dd7a88c371797c2b70ee3/src/GenericFile.php#L19-L35 |
ideil/laravel-generic-file | src/GenericFile.php | GenericFile.moveUploadedFile | public function moveUploadedFile(File $file, $path_pattern = null, $existing_model = null)
{
// get model instance if available
// not use models if $existing_model === false
$model_class = $this->getConfig('store.model');
if (($model_class || $existing_model) && $existing_model !== false) {
$model_instance = $existing_model ?: new $model_class();
// cancel upload if event returned false
if (!$model_instance->beforeUpload($file)) {
return;
}
}
$interpolated = parent::moveUploadedFile($file, $path_pattern);
// check is model available
// and update it
if (isset($model_instance)) {
return $this->saveModelData($model_instance, $interpolated);
}
return $interpolated;
} | php | public function moveUploadedFile(File $file, $path_pattern = null, $existing_model = null)
{
// get model instance if available
// not use models if $existing_model === false
$model_class = $this->getConfig('store.model');
if (($model_class || $existing_model) && $existing_model !== false) {
$model_instance = $existing_model ?: new $model_class();
// cancel upload if event returned false
if (!$model_instance->beforeUpload($file)) {
return;
}
}
$interpolated = parent::moveUploadedFile($file, $path_pattern);
// check is model available
// and update it
if (isset($model_instance)) {
return $this->saveModelData($model_instance, $interpolated);
}
return $interpolated;
} | Move uploaded file to path by pattern and update model.
@param File $file
@param string|null $path_pattern
@param Illuminate\Database\Eloquent\Model|null|false $existing_model
@return Illuminate\Database\Eloquent\Model|string|null | https://github.com/ideil/laravel-generic-file/blob/3eaeadf06dfb295c391dd7a88c371797c2b70ee3/src/GenericFile.php#L46-L73 |
ideil/laravel-generic-file | src/GenericFile.php | GenericFile.fetchUrl | public function fetchUrl($url, $path_pattern = null, $existing_model = null)
{
if ($file = $this->fetchFileByUrl($url)) {
return $this->moveUploadedFile($file, $path_pattern, $existing_model);
}
return;
} | php | public function fetchUrl($url, $path_pattern = null, $existing_model = null)
{
if ($file = $this->fetchFileByUrl($url)) {
return $this->moveUploadedFile($file, $path_pattern, $existing_model);
}
return;
} | @param string $url
@param string $path_pattern
@param Illuminate\Database\Eloquent\Model|null|false $existing_model
@return string|null | https://github.com/ideil/laravel-generic-file/blob/3eaeadf06dfb295c391dd7a88c371797c2b70ee3/src/GenericFile.php#L82-L89 |
ideil/laravel-generic-file | src/GenericFile.php | GenericFile.makeUrlToUploadedFile | public function makeUrlToUploadedFile($model, $path_pattern = null, array $model_map = array(), $domain = null)
{
return parent::makeUrlToUploadedFile($model, $path_pattern,
$model instanceof Model ? $model->getFileAssignMap() : $model_map, $domain);
} | php | public function makeUrlToUploadedFile($model, $path_pattern = null, array $model_map = array(), $domain = null)
{
return parent::makeUrlToUploadedFile($model, $path_pattern,
$model instanceof Model ? $model->getFileAssignMap() : $model_map, $domain);
} | Make url to stored file.
@param array|Illuminate\Database\Eloquent\Model $model
@param string|null $path_pattern
@return string | https://github.com/ideil/laravel-generic-file/blob/3eaeadf06dfb295c391dd7a88c371797c2b70ee3/src/GenericFile.php#L99-L103 |
ideil/laravel-generic-file | src/GenericFile.php | GenericFile.makePathToUploadedFile | public function makePathToUploadedFile($model, $path_pattern = null, array $model_map = array())
{
return parent::makePathToUploadedFile($model, $path_pattern,
$model instanceof Model ? $model->getFileAssignMap() : $model_map);
} | php | public function makePathToUploadedFile($model, $path_pattern = null, array $model_map = array())
{
return parent::makePathToUploadedFile($model, $path_pattern,
$model instanceof Model ? $model->getFileAssignMap() : $model_map);
} | Full path to stored file.
@param array|Illuminate\Database\Eloquent\Model $model
@param string|null $path_pattern
@return string | https://github.com/ideil/laravel-generic-file/blob/3eaeadf06dfb295c391dd7a88c371797c2b70ee3/src/GenericFile.php#L113-L117 |
agilesdesign/flasher | src/Flasher/Support/Notifier.php | Notifier.flash | protected function flash(string $type, string $message, string $level)
{
$group = Session::get($type, new MessageBag());
Session::flash($type, $group->add($level, $message));
return $this;
} | php | protected function flash(string $type, string $message, string $level)
{
$group = Session::get($type, new MessageBag());
Session::flash($type, $group->add($level, $message));
return $this;
} | Flash message to the Session.
@param string $type
@param string $message
@param string $level
@return $this | https://github.com/agilesdesign/flasher/blob/5bf8c04d0a2df55177d3f81983982d5999b9f5b8/src/Flasher/Support/Notifier.php#L49-L56 |
koinephp/DbTestCase | src/Koine/TableHelper/TableHelper.php | TableHelper.selectQuery | private function selectQuery($sql, array $params = array())
{
$stmt = $this->getConnection()->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} | php | private function selectQuery($sql, array $params = array())
{
$stmt = $this->getConnection()->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} | @param string $sql
@param array $params
@return array | https://github.com/koinephp/DbTestCase/blob/60800c019664105484782f441874dd19c58549f0/src/Koine/TableHelper/TableHelper.php#L80-L86 |
koinephp/DbTestCase | src/Koine/TableHelper/TableHelper.php | TableHelper.find | public function find($id)
{
$resultSet = $this->findAllBy(array(
$this->getIdColumn() => $id,
));
if (count($resultSet)) {
return $resultSet[0];
}
throw new \DomainException(
sprintf(
'%s record not found by %s %s',
$this->getTableName(),
$this->getIdColumn(),
$id
)
);
} | php | public function find($id)
{
$resultSet = $this->findAllBy(array(
$this->getIdColumn() => $id,
));
if (count($resultSet)) {
return $resultSet[0];
}
throw new \DomainException(
sprintf(
'%s record not found by %s %s',
$this->getTableName(),
$this->getIdColumn(),
$id
)
);
} | @param int $value
@return array
@throws \DomainException when record is not found | https://github.com/koinephp/DbTestCase/blob/60800c019664105484782f441874dd19c58549f0/src/Koine/TableHelper/TableHelper.php#L130-L148 |
koinephp/DbTestCase | src/Koine/TableHelper/TableHelper.php | TableHelper.findAllBy | public function findAllBy(array $conditions = array())
{
$sql = sprintf('SELECT * FROM %s', $this->getTableName());
$whereConditions = $this->assembleEquality($conditions);
$where = sprintf('WHERE %s', implode(' AND ', $whereConditions));
$sql .= " $where";
return $this->selectQuery($sql, $conditions);
} | php | public function findAllBy(array $conditions = array())
{
$sql = sprintf('SELECT * FROM %s', $this->getTableName());
$whereConditions = $this->assembleEquality($conditions);
$where = sprintf('WHERE %s', implode(' AND ', $whereConditions));
$sql .= " $where";
return $this->selectQuery($sql, $conditions);
} | @param array $conditions
@return array | https://github.com/koinephp/DbTestCase/blob/60800c019664105484782f441874dd19c58549f0/src/Koine/TableHelper/TableHelper.php#L155-L163 |
luxorphp/http-controller | src/Event/Executor.php | Executor.exist | public function exist() {
$this->resCallback = $this->callback->filter(function (HttpCallBack $call) {
return $this->rutesManager->existRutes($call->getPath(), $this->peticion);
});
} | php | public function exist() {
$this->resCallback = $this->callback->filter(function (HttpCallBack $call) {
return $this->rutesManager->existRutes($call->getPath(), $this->peticion);
});
} | Filtrar si existe algun controlador que pueda ser ejecutado
sin importar si es el solicitado, esto se verifica con la longitud
de la rutas almacenada, si coinciden con la ruta de la peticion. | https://github.com/luxorphp/http-controller/blob/4cc60fdf2c16b2701cafcce2ba32cb672794c7e1/src/Event/Executor.php#L111-L119 |
luxorphp/http-controller | src/Event/Executor.php | Executor.compare | public function compare() {
// echo '<br>';
// echo 'Se han encontrado '.$this->resCallback->lenght().' resultados del primer filtro <br>';
$this->resFilter = $this->resCallback->filter(function (HttpCallBack $call) {
return $this->rutesManager->compareRute($call->getPath(), $this->peticion);
});
} | php | public function compare() {
// echo '<br>';
// echo 'Se han encontrado '.$this->resCallback->lenght().' resultados del primer filtro <br>';
$this->resFilter = $this->resCallback->filter(function (HttpCallBack $call) {
return $this->rutesManager->compareRute($call->getPath(), $this->peticion);
});
} | Filtrar si existe alguna ruta que sea identica a la ruta de
la peticion esto se realiza a travez de la verificacion de
patrones en las rutas.
@return null | https://github.com/luxorphp/http-controller/blob/4cc60fdf2c16b2701cafcce2ba32cb672794c7e1/src/Event/Executor.php#L127-L138 |
luxorphp/http-controller | src/Event/Executor.php | Executor.execute | public function execute() {
// echo '<br>';
// echo 'Se han encontrado '.$this->resFilter->lenght().' resultados del segundo filtro <br>';
//Ejecutar controlador raiz por defecto, si no hay ningun resultado posible.
if ($this->resFilter->isEmpty() && $this->rutesManager->isRoot($this->actual, $this->peticion)) {
$this->root();
return;
}
//Ejecutar controlador por defecto, si no hay ningun resultado posible.
if ($this->resFilter->isEmpty()) {
$this->default();
return;
}
//Ejecutar controlador.
$this->resFilter->each(function (HttpCallBack $call) {
$call->call($this->rutesManager->getParameter());
});
} | php | public function execute() {
// echo '<br>';
// echo 'Se han encontrado '.$this->resFilter->lenght().' resultados del segundo filtro <br>';
//Ejecutar controlador raiz por defecto, si no hay ningun resultado posible.
if ($this->resFilter->isEmpty() && $this->rutesManager->isRoot($this->actual, $this->peticion)) {
$this->root();
return;
}
//Ejecutar controlador por defecto, si no hay ningun resultado posible.
if ($this->resFilter->isEmpty()) {
$this->default();
return;
}
//Ejecutar controlador.
$this->resFilter->each(function (HttpCallBack $call) {
$call->call($this->rutesManager->getParameter());
});
} | Ejecutar la ruta encontrada, en caso de no encontrar
nada ejecutar una por defecto
@return null | https://github.com/luxorphp/http-controller/blob/4cc60fdf2c16b2701cafcce2ba32cb672794c7e1/src/Event/Executor.php#L145-L169 |
luxorphp/http-controller | src/Event/Executor.php | Executor.default | private function default() {
$this->callback->filter(function (HttpCallBack $test) {
return !strcmp($test->getPath(), $this->actual.'/**');
})->each(function (HttpCallBack $test) {
$test->call($this->rutesManager->getParameter());
});
} | php | private function default() {
$this->callback->filter(function (HttpCallBack $test) {
return !strcmp($test->getPath(), $this->actual.'/**');
})->each(function (HttpCallBack $test) {
$test->call($this->rutesManager->getParameter());
});
} | Metodo quen ejecuta el controlador por defecto cuando no existe una ruta
posible a ejecutar. | https://github.com/luxorphp/http-controller/blob/4cc60fdf2c16b2701cafcce2ba32cb672794c7e1/src/Event/Executor.php#L175-L187 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/DisplayBlock/Strategies/ConfigurableContentStrategy.php | ConfigurableContentStrategy.show | public function show(ReadBlockInterface $block)
{
$contentSearch = $block->getAttribute('contentSearch');
if (!isset($contentSearch['contentId'])) {
throw new \InvalidArgumentException();
}
$contentId = $contentSearch['contentId'];
$language = $this->currentSiteManager->getSiteLanguage();
$content = $this->contentRepository->findPublishedVersion($contentId, $language);
if ($content) {
$parameters = array(
'class' => $block->getStyle(),
'id' => $block->getId(),
'content' => $content
);
return $this->render(
'OpenOrchestraDisplayBundle:Block/ConfigurableContent:show.html.twig',
$parameters
);
}
throw new ContentNotFoundException($contentId);
} | php | public function show(ReadBlockInterface $block)
{
$contentSearch = $block->getAttribute('contentSearch');
if (!isset($contentSearch['contentId'])) {
throw new \InvalidArgumentException();
}
$contentId = $contentSearch['contentId'];
$language = $this->currentSiteManager->getSiteLanguage();
$content = $this->contentRepository->findPublishedVersion($contentId, $language);
if ($content) {
$parameters = array(
'class' => $block->getStyle(),
'id' => $block->getId(),
'content' => $content
);
return $this->render(
'OpenOrchestraDisplayBundle:Block/ConfigurableContent:show.html.twig',
$parameters
);
}
throw new ContentNotFoundException($contentId);
} | Perform the show action for a block
@param ReadBlockInterface $block
@return Response
@throw ContentNotFoundException | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/DisplayBlock/Strategies/ConfigurableContentStrategy.php#L64-L90 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/DisplayBlock/Strategies/ConfigurableContentStrategy.php | ConfigurableContentStrategy.getCacheTags | public function getCacheTags(ReadBlockInterface $block)
{
return array(
$this->tagManager->formatContentTypeTag($block->getAttribute('contentTypeId')),
$this->tagManager->formatContentIdTag($block->getAttribute('contentId'))
);
} | php | public function getCacheTags(ReadBlockInterface $block)
{
return array(
$this->tagManager->formatContentTypeTag($block->getAttribute('contentTypeId')),
$this->tagManager->formatContentIdTag($block->getAttribute('contentId'))
);
} | Return block specific cache tags
@param ReadBlockInterface $block
@return array | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/DisplayBlock/Strategies/ConfigurableContentStrategy.php#L99-L105 |
ttools/ttools | src/TTools/User.php | User.offsetGet | public function offsetGet($offset)
{
return isset($this->credentials[$offset]) ? $this->credentials[$offset] : null;
} | php | public function offsetGet($offset)
{
return isset($this->credentials[$offset]) ? $this->credentials[$offset] : null;
} | {@inheritdoc} | https://github.com/ttools/ttools/blob/32e6b1d9ffa346db3bbfff46a258f12d0c322819/src/TTools/User.php#L45-L48 |
x2ts/x2ts | src/validator/Validator.php | Validator.str | public function str($key) {
$v = new StringValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function str($key) {
$v = new StringValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param $key
@return StringValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L158-L163 |
x2ts/x2ts | src/validator/Validator.php | Validator.date | public function date($key) {
$v = new DateValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function date($key) {
$v = new DateValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param $key
@return DateValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L170-L175 |
x2ts/x2ts | src/validator/Validator.php | Validator.email | public function email($key) {
$v = new EmailValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function email($key) {
$v = new EmailValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param string $key
@return EmailValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L182-L187 |
x2ts/x2ts | src/validator/Validator.php | Validator.url | public function url($key) {
$v = new UrlValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function url($key) {
$v = new UrlValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param string $key
@return UrlValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L194-L199 |
x2ts/x2ts | src/validator/Validator.php | Validator.tel | public function tel($key) {
$v = new TelValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function tel($key) {
$v = new TelValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param $key
@return TelValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L206-L211 |
x2ts/x2ts | src/validator/Validator.php | Validator.float | public function float($key) {
$v = new FloatValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function float($key) {
$v = new FloatValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param $key
@return FloatValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L218-L223 |
x2ts/x2ts | src/validator/Validator.php | Validator.int | public function int($key) {
$v = new IntegerValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function int($key) {
$v = new IntegerValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param $key
@return IntegerValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L230-L235 |
x2ts/x2ts | src/validator/Validator.php | Validator.dec | public function dec($key) {
$v = new DecimalValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function dec($key) {
$v = new DecimalValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param $key
@return DecimalValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L242-L247 |
x2ts/x2ts | src/validator/Validator.php | Validator.hex | public function hex($key) {
$v = new HexadecimalValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function hex($key) {
$v = new HexadecimalValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param $key
@return HexadecimalValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L254-L259 |
x2ts/x2ts | src/validator/Validator.php | Validator.bool | public function bool($key) {
$v = new BooleanValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function bool($key) {
$v = new BooleanValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param string $key
@return BooleanValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L266-L271 |
x2ts/x2ts | src/validator/Validator.php | Validator.arr | public function arr($key) {
$v = new ArrayValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | php | public function arr($key) {
$v = new ArrayValidator($this->shell->_unsafeVar[$key] ?? null, $this->shell);
$v->_isUndefined = !array_key_exists($key, $this->shell->_unsafeVar);
$this->shell->subValidators[$key] = $v;
return $v;
} | @param string $key
@return ArrayValidator | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L278-L283 |
x2ts/x2ts | src/validator/Validator.php | Validator.selfValidate | protected function selfValidate() {
if ($this->_isUndefined && $this->onUndefinedIgnore) {
$this->_safeVar = null;
$this->_isValid = true;
goto finish;
}
if ($this->isEmpty($this->_unsafeVar)) {
if ($this->onEmptyIgnore) {
$this->_safeVar = null;
$this->_isValid = true;
$this->_isEmpty = true;
goto finish;
} else if ($this->onEmptySet) {
$this->_safeVar = $this->onEmptySetValue;
$this->_isValid = true;
goto finish;
} else if ($this->emptyMessage) {
$this->_isValid = false;
$this->message = $this->emptyMessage;
$this->_isEmpty = true;
} else {
$this->_isEmpty = true;
}
}
if (!$this->_isValid && $this->isEmpty($this->message)) {
if ($this->onErrorSet) {
$this->_safeVar = $this->onErrorSetValue;
$this->_isValid = true;
} else if ($this->errorMessage !== '') {
$this->message = $this->errorMessage;
}
} else {
$this->_safeVar = $this->_unsafeVar;
}
finish:
$this->validated = true;
} | php | protected function selfValidate() {
if ($this->_isUndefined && $this->onUndefinedIgnore) {
$this->_safeVar = null;
$this->_isValid = true;
goto finish;
}
if ($this->isEmpty($this->_unsafeVar)) {
if ($this->onEmptyIgnore) {
$this->_safeVar = null;
$this->_isValid = true;
$this->_isEmpty = true;
goto finish;
} else if ($this->onEmptySet) {
$this->_safeVar = $this->onEmptySetValue;
$this->_isValid = true;
goto finish;
} else if ($this->emptyMessage) {
$this->_isValid = false;
$this->message = $this->emptyMessage;
$this->_isEmpty = true;
} else {
$this->_isEmpty = true;
}
}
if (!$this->_isValid && $this->isEmpty($this->message)) {
if ($this->onErrorSet) {
$this->_safeVar = $this->onErrorSetValue;
$this->_isValid = true;
} else if ($this->errorMessage !== '') {
$this->message = $this->errorMessage;
}
} else {
$this->_safeVar = $this->_unsafeVar;
}
finish:
$this->validated = true;
} | Start validate the valley itself
@return void | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L382-L420 |
x2ts/x2ts | src/validator/Validator.php | Validator.validate | final public function validate(callable $onDataInvalid = null): Validator {
$shell = $this->shell;
if (count($shell->subValidators)) {
$shell->_safeVar = [];
/**
* @var Validator $validator
* @var string $key
*/
foreach ($shell->subValidators as $key => $validator) {
$validator->selfValidate();
if ($validator->_isUndefined && $validator->onUndefinedIgnore) {
continue;
}
if ($validator->_isEmpty && $validator->onEmptyIgnore) {
continue;
}
if ($validator->_isValid) {
$shell->_safeVar[$key] = $validator->safeVar;
} else if ($validator->message !== '') {
$shell->_messages[$key] = $validator->message;
$shell->_isValid = false;
} else {
$shell->_messages[$key] = "$key is invalid";
$shell->_isValid = false;
}
}
$shell->validated = true;
} else {
$this->selfValidate();
if (!$this->_isValid) {
$this->_messages[] = $this->message;
}
}
if (!$shell->_isValid) {
if (is_callable($onDataInvalid)) {
$onDataInvalid($shell->messages, $shell);
} else {
throw new ValidatorException($shell->messages);
}
}
return $shell;
} | php | final public function validate(callable $onDataInvalid = null): Validator {
$shell = $this->shell;
if (count($shell->subValidators)) {
$shell->_safeVar = [];
/**
* @var Validator $validator
* @var string $key
*/
foreach ($shell->subValidators as $key => $validator) {
$validator->selfValidate();
if ($validator->_isUndefined && $validator->onUndefinedIgnore) {
continue;
}
if ($validator->_isEmpty && $validator->onEmptyIgnore) {
continue;
}
if ($validator->_isValid) {
$shell->_safeVar[$key] = $validator->safeVar;
} else if ($validator->message !== '') {
$shell->_messages[$key] = $validator->message;
$shell->_isValid = false;
} else {
$shell->_messages[$key] = "$key is invalid";
$shell->_isValid = false;
}
}
$shell->validated = true;
} else {
$this->selfValidate();
if (!$this->_isValid) {
$this->_messages[] = $this->message;
}
}
if (!$shell->_isValid) {
if (is_callable($onDataInvalid)) {
$onDataInvalid($shell->messages, $shell);
} else {
throw new ValidatorException($shell->messages);
}
}
return $shell;
} | Start validate the whole chain
include the sub valleys
@param callable $onDataInvalid
@return Validator
@throws \x2ts\validator\ValidatorException | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L431-L473 |
x2ts/x2ts | src/validator/Validator.php | Validator.assignTo | final public function assignTo(
IAssignable $target,
callable $onDataInvalid = null
): IAssignable {
$shell = $this->validated ? $this->shell : $this->validate($onDataInvalid);
if ($shell->_isValid && is_array($shell->_safeVar)) {
$target->assign($shell->_safeVar);
}
return $target;
} | php | final public function assignTo(
IAssignable $target,
callable $onDataInvalid = null
): IAssignable {
$shell = $this->validated ? $this->shell : $this->validate($onDataInvalid);
if ($shell->_isValid && is_array($shell->_safeVar)) {
$target->assign($shell->_safeVar);
}
return $target;
} | @param IAssignable $target
@param callable $onDataInvalid
@return IAssignable $target | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/validator/Validator.php#L481-L491 |
4devs/serializer | Mapping/Factory/MetadataFactory.php | MetadataFactory.getMetadataFor | public function getMetadataFor($value, array $context = []): ClassMetadataInterface
{
if (!is_object($value) && !is_string($value)) {
throw new NoSuchMetadataException(sprintf('Cannot create metadata for non-objects. Got: %s', gettype($value)));
}
$class = $this->getClassName($value);
if (isset($this->loadedClasses[$class])) {
return $this->loadedClasses[$class];
}
if (!class_exists($class) && !interface_exists($class) && !trait_exists($class)) {
throw new NoSuchMetadataException(sprintf('The class or interface "%s" does not exist.', $class));
}
$metadata = new ClassMetadata($class);
$r = $metadata->getReflectionClass();
$parents = [];
// Include constraints from the parent class
if ($parent = $r->getParentClass()) {
$parents[] = $parent;
}
$parents = array_merge($parents, $r->getInterfaces(), $r->getTraits());
if ($this->hasMap($class)) {
$this->loader->loadClassMetadata($metadata);
}
foreach ($parents as $parent) {
if ($this->hasMap($parent->name)) {
$metadata->merge($this->getMetadataFor($parent->name));
}
}
return $this->loadedClasses[$class] = $metadata;
} | php | public function getMetadataFor($value, array $context = []): ClassMetadataInterface
{
if (!is_object($value) && !is_string($value)) {
throw new NoSuchMetadataException(sprintf('Cannot create metadata for non-objects. Got: %s', gettype($value)));
}
$class = $this->getClassName($value);
if (isset($this->loadedClasses[$class])) {
return $this->loadedClasses[$class];
}
if (!class_exists($class) && !interface_exists($class) && !trait_exists($class)) {
throw new NoSuchMetadataException(sprintf('The class or interface "%s" does not exist.', $class));
}
$metadata = new ClassMetadata($class);
$r = $metadata->getReflectionClass();
$parents = [];
// Include constraints from the parent class
if ($parent = $r->getParentClass()) {
$parents[] = $parent;
}
$parents = array_merge($parents, $r->getInterfaces(), $r->getTraits());
if ($this->hasMap($class)) {
$this->loader->loadClassMetadata($metadata);
}
foreach ($parents as $parent) {
if ($this->hasMap($parent->name)) {
$metadata->merge($this->getMetadataFor($parent->name));
}
}
return $this->loadedClasses[$class] = $metadata;
} | {@inheritdoc} | https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Mapping/Factory/MetadataFactory.php#L47-L82 |
4devs/serializer | Mapping/Factory/MetadataFactory.php | MetadataFactory.hasMetadataFor | public function hasMetadataFor($value, array $context = []): bool
{
if (!is_object($value) && !is_string($value)) {
return false;
}
$class = $this->getClassName($value);
$has = $this->hasMap($class);
if (!$has) {
$reflection = new \ReflectionClass($class);
/** @var \ReflectionClass[] $list */
$list = array_merge($reflection->getInterfaces(), $reflection->getTraits());
while ($parent = $reflection->getParentClass()) {
if ($has = $this->hasMap($parent->getName())) {
break;
}
$reflection = $parent;
}
if (!$has) {
foreach ($list as $item) {
if ($has = $this->hasMap($item->getName())) {
break;
}
}
}
}
return $has;
} | php | public function hasMetadataFor($value, array $context = []): bool
{
if (!is_object($value) && !is_string($value)) {
return false;
}
$class = $this->getClassName($value);
$has = $this->hasMap($class);
if (!$has) {
$reflection = new \ReflectionClass($class);
/** @var \ReflectionClass[] $list */
$list = array_merge($reflection->getInterfaces(), $reflection->getTraits());
while ($parent = $reflection->getParentClass()) {
if ($has = $this->hasMap($parent->getName())) {
break;
}
$reflection = $parent;
}
if (!$has) {
foreach ($list as $item) {
if ($has = $this->hasMap($item->getName())) {
break;
}
}
}
}
return $has;
} | {@inheritdoc} | https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Mapping/Factory/MetadataFactory.php#L87-L116 |
4devs/serializer | Mapping/Factory/MetadataFactory.php | MetadataFactory.hasMap | private function hasMap($value)
{
$class = $this->getClassName($value);
return isset($this->loadedClasses[$class]) || $this->loader->hasMetadata($class);
} | php | private function hasMap($value)
{
$class = $this->getClassName($value);
return isset($this->loadedClasses[$class]) || $this->loader->hasMetadata($class);
} | @param string $value
@return bool | https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Mapping/Factory/MetadataFactory.php#L133-L138 |
romaricdrigon/OrchestraBundle | EventListener/SecurityListener.php | SecurityListener.getVariables | protected function getVariables(Request $request)
{
$token = $this->securityContext->getToken();
$user = null;
$roles = [];
if ($token instanceof TokenInterface) {
$user = $token->getUser();
if (null !== $this->roleHierarchy) {
$roles = $this->roleHierarchy->getReachableRoles($token->getRoles());
} else {
$roles = $token->getRoles();
}
}
$variables = array(
'token' => $token,
'user' => $user,
// we removed "object" and "request"
'roles' => array_map(function (RoleInterface $role) { return $role->getRole(); }, $roles),
'trust_resolver' => $this->trustResolver,
'security_context' => $this->securityContext,
);
// controller variables should also be accessible: repository, entity...
return array_merge($request->attributes->all(), $variables);
} | php | protected function getVariables(Request $request)
{
$token = $this->securityContext->getToken();
$user = null;
$roles = [];
if ($token instanceof TokenInterface) {
$user = $token->getUser();
if (null !== $this->roleHierarchy) {
$roles = $this->roleHierarchy->getReachableRoles($token->getRoles());
} else {
$roles = $token->getRoles();
}
}
$variables = array(
'token' => $token,
'user' => $user,
// we removed "object" and "request"
'roles' => array_map(function (RoleInterface $role) { return $role->getRole(); }, $roles),
'trust_resolver' => $this->trustResolver,
'security_context' => $this->securityContext,
);
// controller variables should also be accessible: repository, entity...
return array_merge($request->attributes->all(), $variables);
} | code should be sync with Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter | https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/EventListener/SecurityListener.php#L158-L185 |
as3io/modlr | src/Metadata/MetadataFactory.php | MetadataFactory.getMetadataForType | public function getMetadataForType($type)
{
if (null !== $metadata = $this->doLoadMetadata($type)) {
// Found in memory or from cache implementation
return $metadata;
}
// Loop through the type hierarchy (extension) and merge metadata objects.
foreach ($this->driver->getTypeHierarchy($type) as $hierType) {
if (null !== $loaded = $this->doLoadMetadata($hierType)) {
// Found in memory or from cache implementation
$this->mergeMetadata($metadata, $loaded);
continue;
}
// Load from driver source
$loaded = $this->driver->loadMetadataForType($hierType);
if (null === $loaded) {
throw MetadataException::mappingNotFound($type);
}
// Validate the metadata object.
$this->entityUtil->validateMetadata($hierType, $loaded, $this);
// Handle persistence specific loading and validation.
$this->loadPersistenceMetadata($loaded);
// Handle search specific loading and validation.
$this->loadSearchMetadata($loaded);
$this->mergeMetadata($metadata, $loaded);
$this->dispatchMetadataEvent(Events::onMetadataLoad, $loaded);
$this->doPutMetadata($loaded);
}
if (null === $metadata) {
throw MetadataException::mappingNotFound($type);
}
$this->doPutMetadata($metadata);
return $metadata;
} | php | public function getMetadataForType($type)
{
if (null !== $metadata = $this->doLoadMetadata($type)) {
// Found in memory or from cache implementation
return $metadata;
}
// Loop through the type hierarchy (extension) and merge metadata objects.
foreach ($this->driver->getTypeHierarchy($type) as $hierType) {
if (null !== $loaded = $this->doLoadMetadata($hierType)) {
// Found in memory or from cache implementation
$this->mergeMetadata($metadata, $loaded);
continue;
}
// Load from driver source
$loaded = $this->driver->loadMetadataForType($hierType);
if (null === $loaded) {
throw MetadataException::mappingNotFound($type);
}
// Validate the metadata object.
$this->entityUtil->validateMetadata($hierType, $loaded, $this);
// Handle persistence specific loading and validation.
$this->loadPersistenceMetadata($loaded);
// Handle search specific loading and validation.
$this->loadSearchMetadata($loaded);
$this->mergeMetadata($metadata, $loaded);
$this->dispatchMetadataEvent(Events::onMetadataLoad, $loaded);
$this->doPutMetadata($loaded);
}
if (null === $metadata) {
throw MetadataException::mappingNotFound($type);
}
$this->doPutMetadata($metadata);
return $metadata;
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/MetadataFactory.php#L125-L168 |
as3io/modlr | src/Metadata/MetadataFactory.php | MetadataFactory.dispatchMetadataEvent | private function dispatchMetadataEvent($eventName, EntityMetadata $metadata)
{
$metadataArgs = new Events\MetadataArguments($metadata);
$this->dispatcher->dispatch($eventName, $metadataArgs);
} | php | private function dispatchMetadataEvent($eventName, EntityMetadata $metadata)
{
$metadataArgs = new Events\MetadataArguments($metadata);
$this->dispatcher->dispatch($eventName, $metadataArgs);
} | Dispatches a Metadata event
@param string $eventName
@param EntityMetadata $metadata | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/MetadataFactory.php#L176-L180 |
as3io/modlr | src/Metadata/MetadataFactory.php | MetadataFactory.metadataExists | public function metadataExists($type)
{
if (null !== $metadata = $this->doLoadMetadata($type)) {
// Found in memory or from cache implementation
return true;
}
return null !== $this->driver->loadMetadataForType($type);
} | php | public function metadataExists($type)
{
if (null !== $metadata = $this->doLoadMetadata($type)) {
// Found in memory or from cache implementation
return true;
}
return null !== $this->driver->loadMetadataForType($type);
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/MetadataFactory.php#L205-L212 |
as3io/modlr | src/Metadata/MetadataFactory.php | MetadataFactory.loadPersistenceMetadata | private function loadPersistenceMetadata(EntityMetadata $metadata)
{
$persisterKey = $metadata->persistence->getKey();
$persistenceFactory = $this->driver->getPersistenceMetadataFactory($persisterKey);
$persistenceFactory->handleLoad($metadata);
$persistenceFactory->handleValidate($metadata);
return $metadata;
} | php | private function loadPersistenceMetadata(EntityMetadata $metadata)
{
$persisterKey = $metadata->persistence->getKey();
$persistenceFactory = $this->driver->getPersistenceMetadataFactory($persisterKey);
$persistenceFactory->handleLoad($metadata);
$persistenceFactory->handleValidate($metadata);
return $metadata;
} | Handles persistence specific metadata loading.
@param EntityMetadata $metadata
@return EntityMetadata | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/MetadataFactory.php#L288-L296 |
as3io/modlr | src/Metadata/MetadataFactory.php | MetadataFactory.loadSearchMetadata | private function loadSearchMetadata(EntityMetadata $metadata)
{
if (false === $metadata->isSearchEnabled()) {
return $metadata;
}
$clientKey = $metadata->search->getKey();
$searchFactory = $this->driver->getSearchMetadataFactory($clientKey);
$searchFactory->handleLoad($metadata);
$searchFactory->handleValidate($metadata);
return $metadata;
} | php | private function loadSearchMetadata(EntityMetadata $metadata)
{
if (false === $metadata->isSearchEnabled()) {
return $metadata;
}
$clientKey = $metadata->search->getKey();
$searchFactory = $this->driver->getSearchMetadataFactory($clientKey);
$searchFactory->handleLoad($metadata);
$searchFactory->handleValidate($metadata);
return $metadata;
} | Handles search specific metadata loading.
@param EntityMetadata $metadata
@return EntityMetadata | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/MetadataFactory.php#L304-L315 |
as3io/modlr | src/Metadata/MetadataFactory.php | MetadataFactory.doLoadMetadata | private function doLoadMetadata($type)
{
if (null !== $meta = $this->getFromMemory($type)) {
$this->dispatchMetadataEvent(Events::onMetadataCacheLoad, $meta);
// Found in memory.
return $meta;
}
if (null !== $meta = $this->getFromCache($type)) {
// Found in cache.
$this->dispatchMetadataEvent(Events::onMetadataCacheLoad, $meta);
$this->setToMemory($meta);
return $meta;
}
return null;
} | php | private function doLoadMetadata($type)
{
if (null !== $meta = $this->getFromMemory($type)) {
$this->dispatchMetadataEvent(Events::onMetadataCacheLoad, $meta);
// Found in memory.
return $meta;
}
if (null !== $meta = $this->getFromCache($type)) {
// Found in cache.
$this->dispatchMetadataEvent(Events::onMetadataCacheLoad, $meta);
$this->setToMemory($meta);
return $meta;
}
return null;
} | Attempts to load a Metadata instance from a memory or cache source.
@param string $type
@return EntityMetadata|null | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/MetadataFactory.php#L339-L354 |
malenkiki/bah | src/Malenki/Bah/N.php | N.less | public function less($num)
{
self::mustBeNumeric($num, 'Tested number');
if(is_object($num)){
return $this->value < $num->value;
} else {
return $this->value < $num;
}
} | php | public function less($num)
{
self::mustBeNumeric($num, 'Tested number');
if(is_object($num)){
return $this->value < $num->value;
} else {
return $this->value < $num;
}
} | Checks whether current number is less than given one.
This is equivalent of `$n < 3`. So, for example:
$n = new N(M_PI);
$n->less(4); // true
$n->less(3); // false
@see N::lt() An alias
@param mixed $num N or primitive numeric value
@return boolean
@throws \InvalidArgumentException If argument is not numeric-like | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L547-L556 |
malenkiki/bah | src/Malenki/Bah/N.php | N.lte | public function lte($num)
{
self::mustBeNumeric($num, 'Tested number');
if(is_object($num)){
return $this->value <= $num->value;
} else {
return $this->value <= $num;
}
} | php | public function lte($num)
{
self::mustBeNumeric($num, 'Tested number');
if(is_object($num)){
return $this->value <= $num->value;
} else {
return $this->value <= $num;
}
} | Tests whether current number is less than or equal to given one.
This is equivalent of `$n <= 3`. For example;
$n = new N(3);
$n->lte(3); // true
$n->lte(4); // true
$n->lte(1); // false
@see N::le() An alias
@param mixed $num N or numeric value
@return boolean
@throws \InvalidArgumentException If argument is not numeric-like value | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L586-L595 |
malenkiki/bah | src/Malenki/Bah/N.php | N.greater | public function greater($num)
{
self::mustBeNumeric($num, 'Tested number');
if(is_object($num)){
return $this->value > $num->value;
} else {
return $this->value > $num;
}
} | php | public function greater($num)
{
self::mustBeNumeric($num, 'Tested number');
if(is_object($num)){
return $this->value > $num->value;
} else {
return $this->value > $num;
}
} | Tests whether current number is greater than given one.
This is equivalent of `$n > 3`. For example:
$n = new N(M_PI);
$n->greater(2); // true
$n->greater(4); // false
@see N::gt() An alias
@param mixed $num N or numeric value.
@return boolean
@throws \InvalidArgumentException If argument is not numeric-like value | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L625-L634 |
malenkiki/bah | src/Malenki/Bah/N.php | N.gte | public function gte($num)
{
self::mustBeNumeric($num, 'Tested number');
if(is_object($num)){
return $this->value >= $num->value;
} else {
return $this->value >= $num;
}
} | php | public function gte($num)
{
self::mustBeNumeric($num, 'Tested number');
if(is_object($num)){
return $this->value >= $num->value;
} else {
return $this->value >= $num;
}
} | Tests whether current number is greater than or equal to the given number.
This is equivalent of `$n >= 3`. For example:
$n = new N(3);
$n->gte(3); // true
$n->gte(1); // true
$n->gte(5); // false
@throw \InvalidArgumentException If argument is not numeric or N class
@param mixed $num N or numeric value
@return boolean | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L663-L672 |
malenkiki/bah | src/Malenki/Bah/N.php | N.mod | public function mod($mod)
{
self::mustBeNumeric($mod, 'Divisor');
if ($mod instanceof N) {
$mod = $mod->double;
}
if ($mod == 0) {
throw new \InvalidArgumentException('Cannot divide by 0!');
}
return new N(fmod($this->value, $mod));
} | php | public function mod($mod)
{
self::mustBeNumeric($mod, 'Divisor');
if ($mod instanceof N) {
$mod = $mod->double;
}
if ($mod == 0) {
throw new \InvalidArgumentException('Cannot divide by 0!');
}
return new N(fmod($this->value, $mod));
} | Computes modulo of current number
Computes modulo of current number using given number as divisor. Unlike
`mod()` function, this can use integer or float value, into primitive
PHP type or into `\Malenki\Bah\N` object.
Example:
$n = new N(2001);
echo $n->mod(5); // '1';
echo $n->mod(3); // '0'
@see N::modulo() Alias method
@param int|float|double|N $mod Divisor as an integer/float/double-like
value
@return N
@throws \InvalidArgumentException If given number is not valid type
@throws \InvalidArgumentException If given number is zero | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L859-L872 |
malenkiki/bah | src/Malenki/Bah/N.php | N._prime | protected function _prime()
{
if ($this->value < 2) {
return false;
}
if (!$this->_decimal()->zero) {
throw new \RuntimeException(
'You cannot test if number is prime numer if it is not an integer'
);
}
$max = floor(sqrt($this->value));
for ($i = 2; $i <= $max; $i++) {
if ($this->value % $i == 0) {
return false;
}
}
return true;
} | php | protected function _prime()
{
if ($this->value < 2) {
return false;
}
if (!$this->_decimal()->zero) {
throw new \RuntimeException(
'You cannot test if number is prime numer if it is not an integer'
);
}
$max = floor(sqrt($this->value));
for ($i = 2; $i <= $max; $i++) {
if ($this->value % $i == 0) {
return false;
}
}
return true;
} | Checks if current number is prime number
Checks whether current number is prime number. Prime number can only by
divided by itself and by one.
Example:
$n = new N(5);
var_dump($n->prime); // true
$n = new N(6);
var_dump($n->prime); // false
@see N::$prime Magic getter way
@return boolean
@throws \RuntimeException If current number is not an integer. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L908-L929 |
malenkiki/bah | src/Malenki/Bah/N.php | N._divisors | protected function _divisors()
{
if (!$this->_decimal()->zero) {
throw new \RuntimeException('You can only get divisors from integers!');
}
$n = abs($this->value);
$a = new A();
for ($i = 1; $i <= $n; $i++) {
if ($n % $i == 0) {
$a->add(new self($i));
}
}
return $a;
} | php | protected function _divisors()
{
if (!$this->_decimal()->zero) {
throw new \RuntimeException('You can only get divisors from integers!');
}
$n = abs($this->value);
$a = new A();
for ($i = 1; $i <= $n; $i++) {
if ($n % $i == 0) {
$a->add(new self($i));
}
}
return $a;
} | Gets divisors for the current integer numbers.
If current number is negative, divisors will be based on its positive
version.
@throws \RuntimeException If current number is not an integer
@return A Instance of A class | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L940-L956 |
malenkiki/bah | src/Malenki/Bah/N.php | N.pow | public function pow($num)
{
self::mustBeNumeric($num, 'Power calculus');
return new N(
pow(
$this->value,
is_object($num) ? $num->value : $num
)
);
} | php | public function pow($num)
{
self::mustBeNumeric($num, 'Power calculus');
return new N(
pow(
$this->value,
is_object($num) ? $num->value : $num
)
);
} | Computes current number at given power.
Takes current number to raise it at given power.
Example:
$n = new N(3);
echo $n->pow(2); // '9'
echo $n->pow(3); // '27'
@see N::power() Alias
@see N::_square() Alias for sqaure
@see N::_cube() Alias for cube
@param numeric|N $num Power
@return N
@throws \InvalidArgumentException If given power is not numeric-like
value. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L977-L987 |
malenkiki/bah | src/Malenki/Bah/N.php | N.root | public function root($num)
{
self::mustBeNumeric($num, 'Root');
$n = is_object($num) ? $num->value : $num;
if ($n == 0) {
throw new \InvalidArgumentException('Root must be not nul');
}
return new N(pow($this->value, 1 / $n));
} | php | public function root($num)
{
self::mustBeNumeric($num, 'Root');
$n = is_object($num) ? $num->value : $num;
if ($n == 0) {
throw new \InvalidArgumentException('Root must be not nul');
}
return new N(pow($this->value, 1 / $n));
} | Gets nth root of current number.
Gets Nth root of given number.
Example:
$n = new N(8);
echo $n->root(3); // '2'
echo $n->root(1); // '8'
@see N::_sqrt() A shorthand for magic getter to get square roots.
@see N::_cubeRoot() A shorthand for magic getter to get cube roots.
@param numeric|N $num Root
@return N
@throws \InvalidArgumentException If root level is 0. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1082-L1093 |
malenkiki/bah | src/Malenki/Bah/N.php | N._factorial | protected function _factorial()
{
if ($this->value == 0) {
return new N(1);
}
if ($this->value < 0) {
throw new \RuntimeException(
'Cannot get factorial of negative number!'
);
}
if (!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot get factorial of non integer!'
);
}
return new N(array_product(range(1, $this->value)));
} | php | protected function _factorial()
{
if ($this->value == 0) {
return new N(1);
}
if ($this->value < 0) {
throw new \RuntimeException(
'Cannot get factorial of negative number!'
);
}
if (!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot get factorial of non integer!'
);
}
return new N(array_product(range(1, $this->value)));
} | Computes the factorial of current number.
Computes the factorial of current number, the product form 1 to current
integer number.
$n = new N(1);
echo $n->factorial; // 1
echo $n->incr->factorial; // 2
echo $n->incr->factorial; // 6
echo $n->incr->factorial; // 24
echo $n->incr->factorial; // 120
echo $n->incr->factorial; // 720
This method is the runtime part of magic getter `\Malenki\Bah\N::$factorial`;
@see S::$factorial The magic getter `S::$factorial`
@see S::$fact Magic getter alias `S::$fact`
@return N
@throws \RuntimeException If current number is negative or is not an
integer. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1176-L1195 |
malenkiki/bah | src/Malenki/Bah/N.php | N._triangular | protected function _triangular()
{
if ($this->value < 0) {
throw new \RuntimeException(
'Cannot get triangular number of negative number!'
);
}
if (!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot get triangular number of non integer!'
);
}
return new N(($this->value * ($this->value + 1)) / 2);
} | php | protected function _triangular()
{
if ($this->value < 0) {
throw new \RuntimeException(
'Cannot get triangular number of negative number!'
);
}
if (!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot get triangular number of non integer!'
);
}
return new N(($this->value * ($this->value + 1)) / 2);
} | Gets triangular number using current number as one of triangle’s edge.
A triangular number is well defined by [wikipedia’s
article](http://en.wikipedia.org/wiki/Triangular_number).
This method take current number as one side, and then computer the
triangular number.
Example:
$n = new N(4);
echo $n->triangular; // '10'
@see N::$triangular Magic getter way.
@return N
@throws \RuntimeException If current number is negative
@throws \RuntimeException If current number is not an integer | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1232-L1247 |
malenkiki/bah | src/Malenki/Bah/N.php | N.equal | public function equal($num)
{
self::mustBeNumeric($num, 'Test of equality');
if(is_object($num)){
return $this->value == $num->value;
} else {
return $this->value == $num;
}
} | php | public function equal($num)
{
self::mustBeNumeric($num, 'Test of equality');
if(is_object($num)){
return $this->value == $num->value;
} else {
return $this->value == $num;
}
} | Checks if current number is equal to given argument.
This tests current number with given argument, an object or primitive
numeric value.
Example:
$n = new N(5);
var_dump($n->eq(5)); // true
var_dump($n->eq(5.0)); // true
var_dump($n->eq(new N(5))); // true
var_dump($n->eq(new N(5.0))); // true
@see N::notEqual() The opposite test.
@see N::eq() An alias
@throw \InvalidArgumentException If argument is not numeric or N class
@param numeric|N $num N or numeric value.
@return boolean | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1299-L1308 |
malenkiki/bah | src/Malenki/Bah/N.php | N._decimal | protected function _decimal()
{
$sign = 1;
if ($this->value < 0) {
$sign = -1;
}
return new N($sign * (abs($this->value) - floor(abs($this->value))));
} | php | protected function _decimal()
{
$sign = 1;
if ($this->value < 0) {
$sign = -1;
}
return new N($sign * (abs($this->value) - floor(abs($this->value))));
} | Gets decimal part.
Gets decimal part of current number .
Example:
$n = new N(3.14);
echo $n->decimal; // '0.14'
@see N::$decimal The magic getter version `N::$decimal`
@return N | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1433-L1442 |
malenkiki/bah | src/Malenki/Bah/N.php | N._odd | protected function _odd()
{
if((abs($this->value) - floor(abs($this->value))) != 0){
throw new \RuntimeException(
'Testing if number is odd or even only if it is an integer!'
);
}
return (boolean) ($this->value & 1);
} | php | protected function _odd()
{
if((abs($this->value) - floor(abs($this->value))) != 0){
throw new \RuntimeException(
'Testing if number is odd or even only if it is an integer!'
);
}
return (boolean) ($this->value & 1);
} | Tests whether current number is odd.
Tests whether current integer number is odd or not. If current number is
not an integer, then raises an `\RuntimeException`.
This is used as runtime part of magic getter `S::$odd`.
Example:
$n = new N(3);
$n->odd; // true
$n = new N(4);
$n->odd; // false
$n = new N(3.14);
$n->odd; // raises eception
@see S::$odd The magic getter `S::$odd`
$see S::_even() The opposite implementation for even number
@return boolean
@throws \RuntimeException If current number is not an integer | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1466-L1475 |
malenkiki/bah | src/Malenki/Bah/N.php | N.plus | public function plus($number)
{
self::mustBeNumeric($number, 'Value to add');
$number = is_object($number) ? $number->value : $number;
return new self($this->value + $number);
} | php | public function plus($number)
{
self::mustBeNumeric($number, 'Value to add');
$number = is_object($number) ? $number->value : $number;
return new self($this->value + $number);
} | Adds current number to given argument.
Create new `\Malenki\Bah\N` having the sum of given argument with
current number
@param mixed $number Numeric-like value
@return N
@throws \InvalidArgumentException If argument is not N or numeric value. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1583-L1590 |
malenkiki/bah | src/Malenki/Bah/N.php | N.minus | public function minus($number)
{
self::mustBeNumeric($number, 'Value to substract');
$number = is_object($number) ? $number->value : $number;
return new self($this->value - $number);
} | php | public function minus($number)
{
self::mustBeNumeric($number, 'Value to substract');
$number = is_object($number) ? $number->value : $number;
return new self($this->value - $number);
} | Substract current number with other.
Creates new `\Malenki\Bah\N` having the substraction of given argument
with current number
@param mixed $number N or numeric value
@return N
@throws \InvalidArgumentException If argument is not N or numeric value. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1602-L1609 |
malenkiki/bah | src/Malenki/Bah/N.php | N.multiply | public function multiply($number)
{
self::mustBeNumeric($number, 'Value to multiply');
$number = is_object($number) ? $number->value : $number;
return new self($this->value * $number);
} | php | public function multiply($number)
{
self::mustBeNumeric($number, 'Value to multiply');
$number = is_object($number) ? $number->value : $number;
return new self($this->value * $number);
} | Creates new N by multipling the current to the given one
@throw \InvalidArgumentException If argument is not N or numeric value.
@param mixed $number N or numeric value
@return N | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1618-L1625 |
malenkiki/bah | src/Malenki/Bah/N.php | N.divide | public function divide($number)
{
self::mustBeNumeric($number, 'Value to divide');
$number = is_object($number) ? $number->value : $number;
if ($number == 0) {
throw new \InvalidArgumentException('You cannot divide by zero!');
}
return new self($this->value / $number);
} | php | public function divide($number)
{
self::mustBeNumeric($number, 'Value to divide');
$number = is_object($number) ? $number->value : $number;
if ($number == 0) {
throw new \InvalidArgumentException('You cannot divide by zero!');
}
return new self($this->value / $number);
} | Divide current number with given argument.
@throw \InvalidArgumentException If given argument is zero
@throw \InvalidArgumentException If given argument is not N or numeric value.
@param mixed $number N or numeric value
@return N | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1635-L1646 |
malenkiki/bah | src/Malenki/Bah/N.php | N._roman | protected function _roman()
{
if(!$this->_decimal()->zero || $this->value < 0){
throw new \RuntimeException(
'Converting into roman numerals uses only positive integers.'
);
}
$arr_numerals = array(
(object) array(
'integer' => 1000,
'roman' => 'm'
),
(object) array(
'integer' => 900,
'roman' => 'cm'
),
(object) array(
'integer' => 500,
'roman' => 'd'
),
(object) array(
'integer' => 400,
'roman' => 'cd'
),
(object) array(
'integer' => 100,
'roman' => 'c'
),
(object) array(
'integer' => 90,
'roman' => 'xc'
),
(object) array(
'integer' => 50,
'roman' => 'l'
),
(object) array(
'integer' => 40,
'roman' => 'xl'
),
(object) array(
'integer' => 10,
'roman' => 'x'
),
(object) array(
'integer' => 9,
'roman' => 'ix'
),
(object) array(
'integer' => 5,
'roman' => 'v'
),
(object) array(
'integer' => 4,
'roman' => 'iv'
),
(object) array(
'integer' => 1,
'roman' => 'i'
)
);
$int_number = $this->value;
$str_numeral = '';
$str_least = '';
$int_count_numerals = count($arr_numerals);
for ($i = 0; $i < $int_count_numerals; $i++) {
while ($int_number >= $arr_numerals[$i]->integer) {
$str_least .= $arr_numerals[$i]->roman;
$int_number -= $arr_numerals[$i]->integer;
}
}
return new S($str_numeral . $str_least);
} | php | protected function _roman()
{
if(!$this->_decimal()->zero || $this->value < 0){
throw new \RuntimeException(
'Converting into roman numerals uses only positive integers.'
);
}
$arr_numerals = array(
(object) array(
'integer' => 1000,
'roman' => 'm'
),
(object) array(
'integer' => 900,
'roman' => 'cm'
),
(object) array(
'integer' => 500,
'roman' => 'd'
),
(object) array(
'integer' => 400,
'roman' => 'cd'
),
(object) array(
'integer' => 100,
'roman' => 'c'
),
(object) array(
'integer' => 90,
'roman' => 'xc'
),
(object) array(
'integer' => 50,
'roman' => 'l'
),
(object) array(
'integer' => 40,
'roman' => 'xl'
),
(object) array(
'integer' => 10,
'roman' => 'x'
),
(object) array(
'integer' => 9,
'roman' => 'ix'
),
(object) array(
'integer' => 5,
'roman' => 'v'
),
(object) array(
'integer' => 4,
'roman' => 'iv'
),
(object) array(
'integer' => 1,
'roman' => 'i'
)
);
$int_number = $this->value;
$str_numeral = '';
$str_least = '';
$int_count_numerals = count($arr_numerals);
for ($i = 0; $i < $int_count_numerals; $i++) {
while ($int_number >= $arr_numerals[$i]->integer) {
$str_least .= $arr_numerals[$i]->roman;
$int_number -= $arr_numerals[$i]->integer;
}
}
return new S($str_numeral . $str_least);
} | Converts current number to roman number.
This converts current positive integer to roman numerals, returning
`\Malenki\Bah\S` object.
Example:
$n = new N(1979);
echo $n->roman; // 'mcmlxxix'
echo $n->roman->upper; // 'MCMLXXIX'
@return S
@throws \RuntimeException If current number is not an positive integer. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1663-L1740 |
malenkiki/bah | src/Malenki/Bah/N.php | N.greek | public function greek($digamma = true)
{
if(!$this->_decimal()->zero || $this->value < 0){
throw new \RuntimeException(
'Converting into greek uses only positive integers.'
);
}
if ($this->value > 9999) {
throw new \RuntimeException(
'Numbers over 9999 are not yet available for greek format.'
);
}
$keraia = 'ʹ';
$arr_greek = array(
1 => 'α',
2 => 'β',
3 => 'γ',
4 => 'δ',
5 => 'ε',
6 => 'ϝ',
7 => 'ζ',
8 => 'η',
9 => 'θ',
10 => 'ι',
20 => 'κ',
30 => 'λ',
40 => 'μ',
50 => 'ν',
60 => 'ξ',
70 => 'ο',
80 => 'π',
90 => 'ϟ',
100 => 'ρ',
200 => 'σ',
300 => 'τ',
400 => 'υ',
500 => 'φ',
600 => 'χ',
700 => 'ψ',
800 => 'ω',
900 => 'ϡ',
1000 => 'ͺα',
2000 => 'ͺβ',
3000 => 'ͺγ',
4000 => 'ͺδ',
5000 => 'ͺε',
6000 => 'ͺϛ',
7000 => 'ͺζ',
8000 => 'ͺη',
9000 => 'ͺθ'
);
if (!$digamma) {
$arr_greek[6] = 'ϛ';
}
$str_value = strrev((string) $this->value);
$arr_out = array();
for ($i = 0; $i < strlen($str_value); $i++) {
if ($str_value[$i] > 0) {
$arr_out[] = $arr_greek[pow(10, $i) * $str_value[$i]];
}
}
return new S(implode('', array_reverse($arr_out)));
} | php | public function greek($digamma = true)
{
if(!$this->_decimal()->zero || $this->value < 0){
throw new \RuntimeException(
'Converting into greek uses only positive integers.'
);
}
if ($this->value > 9999) {
throw new \RuntimeException(
'Numbers over 9999 are not yet available for greek format.'
);
}
$keraia = 'ʹ';
$arr_greek = array(
1 => 'α',
2 => 'β',
3 => 'γ',
4 => 'δ',
5 => 'ε',
6 => 'ϝ',
7 => 'ζ',
8 => 'η',
9 => 'θ',
10 => 'ι',
20 => 'κ',
30 => 'λ',
40 => 'μ',
50 => 'ν',
60 => 'ξ',
70 => 'ο',
80 => 'π',
90 => 'ϟ',
100 => 'ρ',
200 => 'σ',
300 => 'τ',
400 => 'υ',
500 => 'φ',
600 => 'χ',
700 => 'ψ',
800 => 'ω',
900 => 'ϡ',
1000 => 'ͺα',
2000 => 'ͺβ',
3000 => 'ͺγ',
4000 => 'ͺδ',
5000 => 'ͺε',
6000 => 'ͺϛ',
7000 => 'ͺζ',
8000 => 'ͺη',
9000 => 'ͺθ'
);
if (!$digamma) {
$arr_greek[6] = 'ϛ';
}
$str_value = strrev((string) $this->value);
$arr_out = array();
for ($i = 0; $i < strlen($str_value); $i++) {
if ($str_value[$i] > 0) {
$arr_out[] = $arr_greek[pow(10, $i) * $str_value[$i]];
}
}
return new S(implode('', array_reverse($arr_out)));
} | Converts current number as ancient greek numerals.
It converts current number if and only if it is an positive integer.
If digamma is false, use stigma instead.
Max number is 9999.
Example:
$n = new N(269);
echo $n->greek; // 'σξθ'
@todo add myriad to have more number after 9999.
@see N::$greek Magic getter using digamma
@param boolean $digamma True, use digamme, false, use stigma
@return S
@throws \RuntimeException If current number is not positive integer
@throws \RuntimeException If current number is greater than 9999 | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1763-L1833 |
malenkiki/bah | src/Malenki/Bah/N.php | N.hindi | public function hindi($use_sep = false)
{
$arr = array(
0 => '०',
1 => '१',
2 => '२',
3 => '३',
4 => '४',
5 => '५',
6 => '६',
7 => '७',
8 => '८',
9 => '९'
);
$str = strtr((string) $this->value, $arr);
if($use_sep && mb_strlen($str, C::ENCODING) > 3){
$mb_strrev = function($str){
preg_match_all('/./us', $str, $ar);
return join('',array_reverse($ar[0]));
};
$str = $mb_strrev($str);
$str_first = mb_substr($str, 0, 3, C::ENCODING);
$str_last = mb_substr($str, 3, mb_strlen($str, C::ENCODING), C::ENCODING);
$str_last = implode(
',',
array_map(
function($a){return implode('', $a);},
array_chunk(
preg_split(
'//u', $str_last, -1, PREG_SPLIT_NO_EMPTY
),
2
)
)
);
$str = $mb_strrev($str_first .','.$str_last);
}
return new S($str);
} | php | public function hindi($use_sep = false)
{
$arr = array(
0 => '०',
1 => '१',
2 => '२',
3 => '३',
4 => '४',
5 => '५',
6 => '६',
7 => '७',
8 => '८',
9 => '९'
);
$str = strtr((string) $this->value, $arr);
if($use_sep && mb_strlen($str, C::ENCODING) > 3){
$mb_strrev = function($str){
preg_match_all('/./us', $str, $ar);
return join('',array_reverse($ar[0]));
};
$str = $mb_strrev($str);
$str_first = mb_substr($str, 0, 3, C::ENCODING);
$str_last = mb_substr($str, 3, mb_strlen($str, C::ENCODING), C::ENCODING);
$str_last = implode(
',',
array_map(
function($a){return implode('', $a);},
array_chunk(
preg_split(
'//u', $str_last, -1, PREG_SPLIT_NO_EMPTY
),
2
)
)
);
$str = $mb_strrev($str_first .','.$str_last);
}
return new S($str);
} | Converts current number as hindi numerals.
The current number is converted to hindi numerals.
Example:
$n = new N(123456789);
echo $n->hindi; // '१२३४५६७८९'
$n = new N(123456789);
echo $n->hindi(true); // '१२,३४,५६,७८९'
@param bollean $use_sep If true, then output has separators
@return S
@todo what about decimal? | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1852-L1894 |
malenkiki/bah | src/Malenki/Bah/N.php | N._arabic | protected function _arabic($type = 'arabic')
{
$arr = array(
0 => '٠',
1 => '١',
2 => '٢',
3 => '٣',
4 => '٤',
5 => '٥',
6 => '٦',
7 => '٧',
8 => '٨',
9 => '٩'
);
if($type == 'perso_arabic' || $type == 'persian'){
$arr = array(
0 => '۰',
1 => '۱',
2 => '۲',
3 => '۳',
4 => '۴',
5 => '۵',
6 => '۶',
7 => '۷',
8 => '۸',
9 => '۹'
);
}
return new S(strtr((string) $this->value, $arr));
} | php | protected function _arabic($type = 'arabic')
{
$arr = array(
0 => '٠',
1 => '١',
2 => '٢',
3 => '٣',
4 => '٤',
5 => '٥',
6 => '٦',
7 => '٧',
8 => '٨',
9 => '٩'
);
if($type == 'perso_arabic' || $type == 'persian'){
$arr = array(
0 => '۰',
1 => '۱',
2 => '۲',
3 => '۳',
4 => '۴',
5 => '۵',
6 => '۶',
7 => '۷',
8 => '۸',
9 => '۹'
);
}
return new S(strtr((string) $this->value, $arr));
} | Converts current number as arabic digit.
Arbic number can have their own shape, so many arab countries use arabic
number in place of occidental numerals.
This converts current numbers into `\Malenki\Bah\S` object having arabic
digits.
Example:
$n = new N(1979);
echo $n->arabic; // '١٩٧٩'
@see S::$arabic Magic getter version
@see S::$perso_arabic Magic getter version for perso arabic
@see S::$persian Magic getter version for persian
@param string $type Type of arabic digits: `arabic` (default), or `perso_arabic` or `persian`
@return S | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1916-L1947 |
malenkiki/bah | src/Malenki/Bah/N.php | N.chinese | public function chinese($use_simple_zero = false)
{
// n myriads, so indexed using that.
$arr_myriads = array(
'兆', '吉', '太', '拍', '艾', '泽', '尧'
);
$arr_multiplicators = array(
'千', '百', '十'
);
$arr_units = array(
'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'
);
if($use_simple_zero){
$arr_units[0] = '〇';
}
if($this->_decimal()->zero){
// split into reversed myriads
$arr_groups = str_split(strrev((string) abs($this->value)), 4);
$arr_groups = array_values(array_reverse($arr_groups));
$int_groups_cnt = count($arr_groups);
// reordering all
for($i = 0; $i < $int_groups_cnt; $i++){
$arr_groups[$i] = strrev($arr_groups[$i]);
}
$out = '';
$int_count = $int_groups_cnt - 2;
// ok, we have our divisions, so, let's do it into chinese!
foreach($arr_groups as $k => $v){
$out_prov = '';
$int_abslen = strlen(abs($v));
for($i = 0; $i < $int_abslen; $i++){
$out_prov .= $arr_units[(int) $v[$i]];
if($v[$i] == '0') continue;
if($i < 3){
$arr_prov = $arr_multiplicators;
if($int_abslen != 4){
$arr_prov = array_slice(
$arr_multiplicators,
4 - $int_abslen
);
}
if(isset($arr_prov[$i])){
$out_prov .= $arr_prov[$i];
}
}
}
if(in_array((int) ltrim($v, 0), range(11, 19))){
$out_prov = preg_replace(
'/一十/ui',
'十',
$out_prov
);
}
if(mb_strlen($out_prov, 'UTF-8') > 1){
$out_prov = preg_replace(
'/'.$arr_units[0].'+$/ui',
'',
$out_prov
);
}
$out .= preg_replace(
'/'.$arr_units[0].'+/ui',
$arr_units[0],
$out_prov
);
if($int_count >= 0){
if(isset($arr_myriads[$int_count])){
$out .= $arr_myriads[$int_count];
} else {
throw new \RuntimeException(
'Myriads for this number does not exists, cannot '
.'create number!'
);
}
$int_count--;
}
}
} else {
$part_int = new N(floor(abs($this->value)));
$part_decimal = substr((string) abs($this->_decimal()->float), 2);
$out = $part_int->chinese($use_simple_zero);
$out .= '点' . strtr($part_decimal, $arr_units);
}
if($this->value < 0){
$out = '负' . $out;
}
return new S($out);
} | php | public function chinese($use_simple_zero = false)
{
// n myriads, so indexed using that.
$arr_myriads = array(
'兆', '吉', '太', '拍', '艾', '泽', '尧'
);
$arr_multiplicators = array(
'千', '百', '十'
);
$arr_units = array(
'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'
);
if($use_simple_zero){
$arr_units[0] = '〇';
}
if($this->_decimal()->zero){
// split into reversed myriads
$arr_groups = str_split(strrev((string) abs($this->value)), 4);
$arr_groups = array_values(array_reverse($arr_groups));
$int_groups_cnt = count($arr_groups);
// reordering all
for($i = 0; $i < $int_groups_cnt; $i++){
$arr_groups[$i] = strrev($arr_groups[$i]);
}
$out = '';
$int_count = $int_groups_cnt - 2;
// ok, we have our divisions, so, let's do it into chinese!
foreach($arr_groups as $k => $v){
$out_prov = '';
$int_abslen = strlen(abs($v));
for($i = 0; $i < $int_abslen; $i++){
$out_prov .= $arr_units[(int) $v[$i]];
if($v[$i] == '0') continue;
if($i < 3){
$arr_prov = $arr_multiplicators;
if($int_abslen != 4){
$arr_prov = array_slice(
$arr_multiplicators,
4 - $int_abslen
);
}
if(isset($arr_prov[$i])){
$out_prov .= $arr_prov[$i];
}
}
}
if(in_array((int) ltrim($v, 0), range(11, 19))){
$out_prov = preg_replace(
'/一十/ui',
'十',
$out_prov
);
}
if(mb_strlen($out_prov, 'UTF-8') > 1){
$out_prov = preg_replace(
'/'.$arr_units[0].'+$/ui',
'',
$out_prov
);
}
$out .= preg_replace(
'/'.$arr_units[0].'+/ui',
$arr_units[0],
$out_prov
);
if($int_count >= 0){
if(isset($arr_myriads[$int_count])){
$out .= $arr_myriads[$int_count];
} else {
throw new \RuntimeException(
'Myriads for this number does not exists, cannot '
.'create number!'
);
}
$int_count--;
}
}
} else {
$part_int = new N(floor(abs($this->value)));
$part_decimal = substr((string) abs($this->_decimal()->float), 2);
$out = $part_int->chinese($use_simple_zero);
$out .= '点' . strtr($part_decimal, $arr_units);
}
if($this->value < 0){
$out = '负' . $out;
}
return new S($out);
} | Converts current number into chinese numerals
The current number is converted into simplified chinese ideograms.
As argument, you can use a boolean to use alternative zero numeral. By
default it does not use simple zero.
Example:
$n = new N(1234);
echo $n->chinese; // '一千二百三十四'
echo $n->mandarin; // '一千二百三十四'
echo $n->putonghua; // '一千二百三十四'
$n = new N(208);
echo $n->chinese(false); // '二百零八'
echo $n->chinese; // '二百零八'
echo $n->mandarin; // '二百零八'
echo $n->putonghua; // '二百零八'
echo $n->chinese(true); // '二百〇八'
echo $n->chinese_other_zero; // '二百〇八'
echo $n->mandarin_other_zero; // '二百〇八'
echo $n->putonghua_other_zero; // '二百〇八'
__Note:__ Several magic getters are available, for each " alternatives,
you can add `_other_zero` to have same result as `N::chinese(true)`.
@see N::$chinse Magic getter way
@see N::$mandarin Other magic getter way
@see N::$putonghua Last magic getter way
@param boolean $use_simple_zero use or not simple zero.
@return S
@throws \RuntimeException If at least one myriad does not exist for current number. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L1983-L2095 |
malenkiki/bah | src/Malenki/Bah/N.php | N._hex | protected function _hex()
{
if(!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot get hexadecimal numbers from non integer.'
);
}
if($this->value < 0){
return new S('-' . dechex(abs($this->value)));
} else {
return new S(dechex($this->value));
}
} | php | protected function _hex()
{
if(!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot get hexadecimal numbers from non integer.'
);
}
if($this->value < 0){
return new S('-' . dechex(abs($this->value)));
} else {
return new S(dechex($this->value));
}
} | Converts to hexadecimal number.
Returns current integer number converted to hexadecimal as
`\Malenki\Bah\S` object.
Example:
$n = new N(2001);
echo $n->hex; // '7d1'
Negative numbers are allowed too:
$n = new N(-2001);
echo $n->hex; // '-7d1'
This is runtime part of its associated magic getter.
@see N::$hex Magic getter `N::$hex`
@see N::_h() Alias
@return S
@throws \RuntimeException If current number is not an integer. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L2143-L2156 |
malenkiki/bah | src/Malenki/Bah/N.php | N._oct | protected function _oct()
{
if(!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot get octal numbers from non integer.'
);
}
if($this->value < 0){
return new S('-' . decoct(abs($this->value)));
} else {
return new S(decoct($this->value));
}
} | php | protected function _oct()
{
if(!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot get octal numbers from non integer.'
);
}
if($this->value < 0){
return new S('-' . decoct(abs($this->value)));
} else {
return new S(decoct($this->value));
}
} | Converts to octal number.
Returns current integer number converted to octal as `\Malenki\Bah\S`
object.
Example:
$n = new N(2001);
echo $n->oct; // '3721'
Negative numbers are allowed too:
$n = new N(-2001);
echo $n->oct; // '-3721'
This is runtime part of its associated magic getter.
@see N::$oct Magic getter `N::$oct`
@see N::_o() Alias
@return S
@throws \RuntimeException If current number is not an integer. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L2182-L2196 |
malenkiki/bah | src/Malenki/Bah/N.php | N._bin | protected function _bin()
{
if(!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot get binary numbers from non integer.'
);
}
if($this->value < 0){
return new S('-'.decbin(abs($this->value)));
} else {
return new S(decbin($this->value));
}
} | php | protected function _bin()
{
if(!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot get binary numbers from non integer.'
);
}
if($this->value < 0){
return new S('-'.decbin(abs($this->value)));
} else {
return new S(decbin($this->value));
}
} | Converts to binary number.
Returns current integer number converted to binary as `\Malenki\Bah\S`
object.
Example:
$n = new N(2001);
echo $n->bin; // '11111010001'
Negative numbers are allowed too:
$n = new N(-2001);
echo $n->bin; // '-11111010001'
This is runtime part of its associated magic getter.
@see N::$bin Magic getter `N::$bin`
@see N::_b() Alias
@return S
@throws \RuntimeException If current number is not an integer. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L2223-L2237 |
malenkiki/bah | src/Malenki/Bah/N.php | N.base | public function base($n)
{
self::mustBeInteger($n, 'Base');
if(!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot convert to another base from non integer value.'
);
}
$n = is_object($n) ? $n->int : $n;
if (!is_numeric($n) || $n < 2 || $n > 36) {
throw new \InvalidArgumentException(
'Base must be an integer or \Malenki\Bah\N value from 2 '
.'to 36 inclusive.'
);
}
return new S(
($this->value < 0 ? '-' : '') . base_convert($this->value, 10, $n)
);
} | php | public function base($n)
{
self::mustBeInteger($n, 'Base');
if(!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot convert to another base from non integer value.'
);
}
$n = is_object($n) ? $n->int : $n;
if (!is_numeric($n) || $n < 2 || $n > 36) {
throw new \InvalidArgumentException(
'Base must be an integer or \Malenki\Bah\N value from 2 '
.'to 36 inclusive.'
);
}
return new S(
($this->value < 0 ? '-' : '') . base_convert($this->value, 10, $n)
);
} | Converts current number into another base.
This converts current number to another base. Alowed bases are into the
range `[2, 36]`.
$n = new N(2001);
echo $n->base(2); // '11111010001'
You can have negative result too:
$n = new N(-2001);
echo $n->base(2); // '-11111010001'
@see S::$bin Shorthand for base 2
@see S::$oct Shorthand for base 8
@see S::$hex Shorthand for base 16
@see S::$b Another shorthand for base 2
@see S::$o Another shorthand for base 8
@see S::$h Another shorthand for base 16
@param mixed $n Base as integer-like value.
@return S
@throws \RuntimeException If current number is not an integer.
@throws \InvalidArgumentException If given base number is not an
Integer-like value. | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L2336-L2359 |
malenkiki/bah | src/Malenki/Bah/N.php | N.times | public function times($callback)
{
self::mustBeCallable($callback);
if(!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot iterate given callback when number is not integer.'
);
}
if($this->value == 0){
throw new \RuntimeException(
'Cannot iterate given callback on a void range.'
);
}
if($this->value > 0){
$arr_range = range(0, $this->value - 1);
} else {
$arr_range = range($this->value + 1, 0);
}
$a = new A();
foreach($arr_range as $idx){
$idx = new N($idx);
$a->add($callback($idx));
}
return $a;
} | php | public function times($callback)
{
self::mustBeCallable($callback);
if(!$this->_decimal()->zero) {
throw new \RuntimeException(
'Cannot iterate given callback when number is not integer.'
);
}
if($this->value == 0){
throw new \RuntimeException(
'Cannot iterate given callback on a void range.'
);
}
if($this->value > 0){
$arr_range = range(0, $this->value - 1);
} else {
$arr_range = range($this->value + 1, 0);
}
$a = new A();
foreach($arr_range as $idx){
$idx = new N($idx);
$a->add($callback($idx));
}
return $a;
} | Repeats given callable param.
Runs N times given callable param. N is current number.
As argument, callable params as current index of iteration as
`\Malenki\Bah\N` object.
If callable param returns content, then each returned result is stored
into an `\Malenki\Bah\A` object.
Example:
$n = new N(7);
$func = function($i){
if($i->odd){
return true;
}
return false;
};
var_dump($n->times($func)->array); // array(false, true, false, true, false, true, false)
__Note:__ Current number can be negative, but cannot be zero
@param mixed $callback A callable action
@return N
@throws \InvalidArgumentException If param is not callable
@throws \RuntimeException If number is not an integer
@throws \RuntimeException If number is zero | https://github.com/malenkiki/bah/blob/23495014acec63c2790e8021c75bc97d7e04a9c7/src/Malenki/Bah/N.php#L2395-L2425 |
rackberg/para | src/Configuration/AbstractConfiguration.php | AbstractConfiguration.load | public function load(string $fileName = null): void
{
if (!$fileName) {
$fileName = $this->configFile;
}
if (file_exists($fileName)) {
$content = file_get_contents($fileName);
if (false !== $content) {
$this->configuration = $this->parser->parse($content);
}
}
} | php | public function load(string $fileName = null): void
{
if (!$fileName) {
$fileName = $this->configFile;
}
if (file_exists($fileName)) {
$content = file_get_contents($fileName);
if (false !== $content) {
$this->configuration = $this->parser->parse($content);
}
}
} | {@inheritdoc} | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Configuration/AbstractConfiguration.php#L63-L74 |
rackberg/para | src/Configuration/AbstractConfiguration.php | AbstractConfiguration.save | public function save(string $fileName = null): bool
{
if (!$fileName) {
$fileName = $this->configFile;
}
$content = $this->dumper->dump($this->configuration);
return file_put_contents($fileName, $content);
} | php | public function save(string $fileName = null): bool
{
if (!$fileName) {
$fileName = $this->configFile;
}
$content = $this->dumper->dump($this->configuration);
return file_put_contents($fileName, $content);
} | {@inheritdoc} | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Configuration/AbstractConfiguration.php#L79-L86 |
hal-platform/hal-core | src/Entity/Job/JobEvent.php | JobEvent.withStage | public function withStage(string $stage): self
{
$this->stage = JobEventStageEnum::ensureValid($stage);
return $this;
} | php | public function withStage(string $stage): self
{
$this->stage = JobEventStageEnum::ensureValid($stage);
return $this;
} | @param string $stage
@return self | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Entity/Job/JobEvent.php#L125-L129 |
hal-platform/hal-core | src/Entity/Job/JobEvent.php | JobEvent.withStatus | public function withStatus(string $status): self
{
$this->status = JobEventStatusEnum::ensureValid($status);
return $this;
} | php | public function withStatus(string $status): self
{
$this->status = JobEventStatusEnum::ensureValid($status);
return $this;
} | @param string $status
@return self | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Entity/Job/JobEvent.php#L136-L140 |
PhoxPHP/Glider | src/Schema/Scheme.php | Scheme.id | public function id(String $name = 'id', int $length = 15, Bool $null = false)
{
return $this->integer($name, $length, $null, true, ['primary' => true]);
} | php | public function id(String $name = 'id', int $length = 15, Bool $null = false)
{
return $this->integer($name, $length, $null, true, ['primary' => true]);
} | Represents an auto incremented field with a primary key index.
@param $name String
@param $length Integer
@param $null Boolean
@access public
@return Object Kit\Glider\Schema\Column\Type\Contract\TypeContract | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Schema/Scheme.php#L106-L109 |
PhoxPHP/Glider | src/Schema/Scheme.php | Scheme.varchar | public function varchar(String $name, int $length=15, Bool $null=false, Bool $autoIncrement=false, Array $options=[])
{
return $this->setType('Varchar', $name, $length, $null, $autoIncrement, $options);
} | php | public function varchar(String $name, int $length=15, Bool $null=false, Bool $autoIncrement=false, Array $options=[])
{
return $this->setType('Varchar', $name, $length, $null, $autoIncrement, $options);
} | Represents a variable-length non-binary string field.
@param $name String
@param $length Integer
@param $null Boolean
@param $autoIncrement Boolean
@param $options Array
@access public
@return Object Kit\Glider\Schema\Column\Type\Contract\TypeContract | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Schema/Scheme.php#L122-L125 |
PhoxPHP/Glider | src/Schema/Scheme.php | Scheme.decimal | public function decimal(String $name, $length=15, Bool $null=false, Bool $autoIncrement=false, Array $options=[])
{
return $this->setType('Decimal', $name, $length, $null, $autoIncrement, $options);
} | php | public function decimal(String $name, $length=15, Bool $null=false, Bool $autoIncrement=false, Array $options=[])
{
return $this->setType('Decimal', $name, $length, $null, $autoIncrement, $options);
} | Represents a fixed-point number field.
@param $name String
@param $length Integer
@param $null Boolean
@param $autoIncrement Boolean
@param $options Array
@access public
@return Object Kit\Glider\Schema\Column\Type\Contract\TypeContract | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Schema/Scheme.php#L250-L253 |
PhoxPHP/Glider | src/Schema/Scheme.php | Scheme.date | public function date(String $name, Bool $null = false, Array $options = [])
{
return $this->setType('Date', $name, null, $null, false, $options);
} | php | public function date(String $name, Bool $null = false, Array $options = [])
{
return $this->setType('Date', $name, null, $null, false, $options);
} | Represents a date field.
@param $name String
@param $null Boolean
@param $options Array
@access public
@return Object Kit\Glider\Schema\Column\Type\Contract\TypeContract
@since 1.4.6 | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Schema/Scheme.php#L393-L396 |
PhoxPHP/Glider | src/Schema/Scheme.php | Scheme.foreign | public function foreign(String $keyName, Array $options=[], String $onDelete='NO ACTION', String $onUpdate='NO ACTION')
{
$columns = $options['columns'];
$referenceTable = $options['references'];
$refColumns = $options['refColumns'];
$clauseList = ['CASCADE', 'RESTRICT', 'NO ACTION'];
if (is_array($columns)) {
$columns = implode(',', $columns);
}
if (is_array($refColumns)) {
$refColumns = implode(',', $refColumns);
}
$onDelete = strtoupper($onDelete);
$onUpdate = strtoupper($onUpdate);
if (!in_array($onDelete, $clauseList)) {
$onDelete = $clauseList[2];
}
if (!in_array($onUpdate, $clauseList)) {
$onUpdate = $clauseList[2];
}
$definition = 'FOREIGN KEY ' . $keyName . '(' . $columns . ') REFERENCES ' . $referenceTable . '(' . $refColumns . ')';
$definition .= ' ON UPDATE ' . $onUpdate . ' ON DELETE ' . $onDelete;
$options['type'] = 'FOREIGN';
$options['definition'] = $definition;
Scheme::$commandsArray[$keyName] = $options;
Scheme::$commands[] = $definition;
} | php | public function foreign(String $keyName, Array $options=[], String $onDelete='NO ACTION', String $onUpdate='NO ACTION')
{
$columns = $options['columns'];
$referenceTable = $options['references'];
$refColumns = $options['refColumns'];
$clauseList = ['CASCADE', 'RESTRICT', 'NO ACTION'];
if (is_array($columns)) {
$columns = implode(',', $columns);
}
if (is_array($refColumns)) {
$refColumns = implode(',', $refColumns);
}
$onDelete = strtoupper($onDelete);
$onUpdate = strtoupper($onUpdate);
if (!in_array($onDelete, $clauseList)) {
$onDelete = $clauseList[2];
}
if (!in_array($onUpdate, $clauseList)) {
$onUpdate = $clauseList[2];
}
$definition = 'FOREIGN KEY ' . $keyName . '(' . $columns . ') REFERENCES ' . $referenceTable . '(' . $refColumns . ')';
$definition .= ' ON UPDATE ' . $onUpdate . ' ON DELETE ' . $onDelete;
$options['type'] = 'FOREIGN';
$options['definition'] = $definition;
Scheme::$commandsArray[$keyName] = $options;
Scheme::$commands[] = $definition;
} | Generates a foreign key constraint.
@param $keyName <String>
@param $options <Array>
@param $onDelete <String>
@param $onUpdate <String>
@access public
@return <void> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Schema/Scheme.php#L517-L552 |
PhoxPHP/Glider | src/Schema/Scheme.php | Scheme.getDefinition | public function getDefinition($separator=',')
{
$commands = self::$commands;
if (sizeof($commands) > 0) {
return implode($separator, $commands);
}
return null;
} | php | public function getDefinition($separator=',')
{
$commands = self::$commands;
if (sizeof($commands) > 0) {
return implode($separator, $commands);
}
return null;
} | Returns type sql definition.
@access public
@return <Mixed> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Schema/Scheme.php#L560-L569 |
PhoxPHP/Glider | src/Schema/Scheme.php | Scheme.setType | protected function setType(String $type, String $name, $length, Bool $null, Bool $autoIncrement, Array $options)
{
$definition = $name;
$isNull = ' NOT NULL';
$canAutoIncrement = ' AUTO_INCREMENT';
$isPrimary = (isset($options['primary']) && $options['primary'] == true) ? ' PRIMARY KEY' : '';
$index = '';
$type = ucfirst($type);
if (!class_exists($this->typeNamespace . '\\' . $type)) {
throw new RuntimeException(sprintf('Class for type %s does not exist.', $type));
}
$type = $this->typeNamespace . '\\' . $type;
$typeClass = new $type();
$dataType = $typeClass->getName();
$diffTypes = ['DECIMAL', 'DOUBLE', 'TEXT', 'LONGTEXT', 'MEDIUMTEXT', 'LONGTEXT', 'FOREIGN'];
if ($length < $typeClass->getMinimumLength() || $length > $typeClass->getMaximumLength() && !in_array($dataType, $diffTypes)) {
throw new RuntimeException(sprintf('Invalid length for column %s', $name));
}
if (is_array($length)) {
$length = implode(',', $length);
}
if ($null == true) {
$isNull = ' NULL';
}
if ($autoIncrement == false) {
$canAutoIncrement = '';
}
$definition = $name . ' ' . $typeClass->getName();
$definition = $this->getLength($definition, $length);
if (isset($options['unsigned']) && $options['unsigned'] == true) {
$definition .= ' UNSIGNED';
}
$definition .= $isNull . $isPrimary . $canAutoIncrement;
if (isset($options['default'])) {
$definition .= ' DEFAULT ' . $options['default'];
}
Scheme::$commandsArray[$name] = ['type' => $dataType, 'definition' => $definition];
Scheme::$commands[] = $definition;
return $this;
} | php | protected function setType(String $type, String $name, $length, Bool $null, Bool $autoIncrement, Array $options)
{
$definition = $name;
$isNull = ' NOT NULL';
$canAutoIncrement = ' AUTO_INCREMENT';
$isPrimary = (isset($options['primary']) && $options['primary'] == true) ? ' PRIMARY KEY' : '';
$index = '';
$type = ucfirst($type);
if (!class_exists($this->typeNamespace . '\\' . $type)) {
throw new RuntimeException(sprintf('Class for type %s does not exist.', $type));
}
$type = $this->typeNamespace . '\\' . $type;
$typeClass = new $type();
$dataType = $typeClass->getName();
$diffTypes = ['DECIMAL', 'DOUBLE', 'TEXT', 'LONGTEXT', 'MEDIUMTEXT', 'LONGTEXT', 'FOREIGN'];
if ($length < $typeClass->getMinimumLength() || $length > $typeClass->getMaximumLength() && !in_array($dataType, $diffTypes)) {
throw new RuntimeException(sprintf('Invalid length for column %s', $name));
}
if (is_array($length)) {
$length = implode(',', $length);
}
if ($null == true) {
$isNull = ' NULL';
}
if ($autoIncrement == false) {
$canAutoIncrement = '';
}
$definition = $name . ' ' . $typeClass->getName();
$definition = $this->getLength($definition, $length);
if (isset($options['unsigned']) && $options['unsigned'] == true) {
$definition .= ' UNSIGNED';
}
$definition .= $isNull . $isPrimary . $canAutoIncrement;
if (isset($options['default'])) {
$definition .= ' DEFAULT ' . $options['default'];
}
Scheme::$commandsArray[$name] = ['type' => $dataType, 'definition' => $definition];
Scheme::$commands[] = $definition;
return $this;
} | Sets the given column/field type.
@param $type <String>
@param $name <String>
@param $length <Integer>
@param $null <Boolean>
@param $autoIncrement <Boolean>
@param $primary <Boolean>
@access protected
@return <String> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Schema/Scheme.php#L595-L650 |
SpoonX/SxBootstrap | src/SxBootstrap/View/Helper/Bootstrap/Alert.php | Alert.render | public function render()
{
if ($this->closable) {
$this->createDismissButton();
}
$this->getElement()->setAppendContent();
return $this->getElement()->render();
} | php | public function render()
{
if ($this->closable) {
$this->createDismissButton();
}
$this->getElement()->setAppendContent();
return $this->getElement()->render();
} | Render an Alert
@return string | https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Alert.php#L97-L106 |
comoyi/redis | src/Redis/RedisClient.php | RedisClient.getMasterConfigs | protected function getMasterConfigs() {
if('sentinel' === $this->configs['type']) {
return $this->getMasterConfigsBySentinel();
}
$randomMaster = rand(0, (count($this->configs['direct']['masters']) - 1)); // 随机取一个master的配置
$config = [
'host' => $this->configs['direct']['masters'][$randomMaster]['host'],
'port' => $this->configs['direct']['masters'][$randomMaster]['port'],
'password' => $this->configs['password'],
];
return $config;
} | php | protected function getMasterConfigs() {
if('sentinel' === $this->configs['type']) {
return $this->getMasterConfigsBySentinel();
}
$randomMaster = rand(0, (count($this->configs['direct']['masters']) - 1)); // 随机取一个master的配置
$config = [
'host' => $this->configs['direct']['masters'][$randomMaster]['host'],
'port' => $this->configs['direct']['masters'][$randomMaster]['port'],
'password' => $this->configs['password'],
];
return $config;
} | 获取master配置 | https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L112-L123 |
comoyi/redis | src/Redis/RedisClient.php | RedisClient.getSlaveConfigs | protected function getSlaveConfigs() {
if('sentinel' === $this->configs['type']) {
return $this->getSlaveConfigsBySentinel();
}
if(0 === count($this->configs['direct']['slaves'])) { // 没有slave则取master
return $this->getMasterConfigs();
}
$randomSlave = rand(0, (count($this->configs['direct']['slaves']) - 1)); // 随机取一个slave的配置
$config = [
'host' => $this->configs['direct']['slaves'][$randomSlave]['host'],
'port' => $this->configs['direct']['slaves'][$randomSlave]['port'],
'password' => $this->configs['password'],
];
return $config;
} | php | protected function getSlaveConfigs() {
if('sentinel' === $this->configs['type']) {
return $this->getSlaveConfigsBySentinel();
}
if(0 === count($this->configs['direct']['slaves'])) { // 没有slave则取master
return $this->getMasterConfigs();
}
$randomSlave = rand(0, (count($this->configs['direct']['slaves']) - 1)); // 随机取一个slave的配置
$config = [
'host' => $this->configs['direct']['slaves'][$randomSlave]['host'],
'port' => $this->configs['direct']['slaves'][$randomSlave]['port'],
'password' => $this->configs['password'],
];
return $config;
} | 获取slave配置 | https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L128-L142 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.