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
|
---|---|---|---|---|---|---|---|
courtney-miles/schnoop-schema | src/MySQL/Constraint/ForeignKey.php | ForeignKey.hasForeignKeyColumn | public function hasForeignKeyColumn($columnName)
{
foreach ($this->foreignKeyColumns as $fkColumn) {
if ($fkColumn->getColumnName() == $columnName) {
return true;
}
}
return false;
} | php | public function hasForeignKeyColumn($columnName)
{
foreach ($this->foreignKeyColumns as $fkColumn) {
if ($fkColumn->getColumnName() == $columnName) {
return true;
}
}
return false;
} | {@inheritdoc} | https://github.com/courtney-miles/schnoop-schema/blob/f96e9922257860171ecdcdbb6b78182276e2f60d/src/MySQL/Constraint/ForeignKey.php#L157-L166 |
courtney-miles/schnoop-schema | src/MySQL/Constraint/ForeignKey.php | ForeignKey.setForeignKeyColumns | public function setForeignKeyColumns(array $foreignKeyColumns)
{
$this->foreignKeyColumns = [];
foreach ($foreignKeyColumns as $foreignKeyColumn) {
$this->addForeignKeyColumn($foreignKeyColumn);
}
} | php | public function setForeignKeyColumns(array $foreignKeyColumns)
{
$this->foreignKeyColumns = [];
foreach ($foreignKeyColumns as $foreignKeyColumn) {
$this->addForeignKeyColumn($foreignKeyColumn);
}
} | {@inheritdoc} | https://github.com/courtney-miles/schnoop-schema/blob/f96e9922257860171ecdcdbb6b78182276e2f60d/src/MySQL/Constraint/ForeignKey.php#L171-L178 |
courtney-miles/schnoop-schema | src/MySQL/Constraint/ForeignKey.php | ForeignKey.getDDL | public function getDDL()
{
return implode(
' ',
array_filter(
[
'CONSTRAINT `' . $this->getName() . '`',
strtoupper($this->getConstraintType()),
$this->makeIndexedColumnsDDL(),
'REFERENCES',
$this->makeReferenceColumnDDL(),
'ON DELETE ' . $this->getOnDeleteAction(),
'ON UPDATE ' . $this->getOnUpdateAction()
]
)
);
} | php | public function getDDL()
{
return implode(
' ',
array_filter(
[
'CONSTRAINT `' . $this->getName() . '`',
strtoupper($this->getConstraintType()),
$this->makeIndexedColumnsDDL(),
'REFERENCES',
$this->makeReferenceColumnDDL(),
'ON DELETE ' . $this->getOnDeleteAction(),
'ON UPDATE ' . $this->getOnUpdateAction()
]
)
);
} | {@inheritdoc} | https://github.com/courtney-miles/schnoop-schema/blob/f96e9922257860171ecdcdbb6b78182276e2f60d/src/MySQL/Constraint/ForeignKey.php#L213-L229 |
ben-gibson/foursquare-venue-client | src/Factory/Tip/TipFactory.php | TipFactory.create | public function create(Description $description)
{
return new Tip(
new Identifier($description->getMandatoryProperty('id')),
$description->getMandatoryProperty('text'),
$description->getMandatoryProperty('type'),
$description->getMandatoryProperty('agreeCount'),
$description->getMandatoryProperty('disagreeCount')
);
} | php | public function create(Description $description)
{
return new Tip(
new Identifier($description->getMandatoryProperty('id')),
$description->getMandatoryProperty('text'),
$description->getMandatoryProperty('type'),
$description->getMandatoryProperty('agreeCount'),
$description->getMandatoryProperty('disagreeCount')
);
} | Create a tip from a description.
@param Description $description The tip description.
@return Tip | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Factory/Tip/TipFactory.php#L21-L30 |
PHPColibri/framework | Util/File.php | File.getMimeType | public static function getMimeType($filePath)
{
$fInfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($fInfo, $filePath);
finfo_close($fInfo);
return $mime;
} | php | public static function getMimeType($filePath)
{
$fInfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($fInfo, $filePath);
finfo_close($fInfo);
return $mime;
} | Get mime-type og the file.
@param string $filePath
@throws \Exception
@return string string with mime-type like 'image/jpeg' & etc | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Util/File.php#L18-L25 |
atelierspierrot/patterns | src/Patterns/Abstracts/AbstractSingleton.php | AbstractSingleton.& | public static function &getInstance()
{
$classname = get_called_class();
if (!isset(self::$_instances[ $classname ])) {
self::createInstance($classname, func_get_args());
}
$instance = self::$_instances[ $classname ];
return $instance;
} | php | public static function &getInstance()
{
$classname = get_called_class();
if (!isset(self::$_instances[ $classname ])) {
self::createInstance($classname, func_get_args());
}
$instance = self::$_instances[ $classname ];
return $instance;
} | Static object getter: creation of an instance of the current calling class
@param any You can define as many parameters as wanted, they will be passed to
the `__construct` or `init` methods
@return object This may return an instance of an object | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Abstracts/AbstractSingleton.php#L88-L96 |
atelierspierrot/patterns | src/Patterns/Abstracts/AbstractSingleton.php | AbstractSingleton.& | public static function &getInstanceByClassname($classname)
{
$arguments = func_get_args();
array_shift($arguments);
if (!isset(self::$_instances[ $classname ])) {
self::createInstance($classname, $arguments);
}
$instance = self::$_instances[ $classname ];
return $instance;
} | php | public static function &getInstanceByClassname($classname)
{
$arguments = func_get_args();
array_shift($arguments);
if (!isset(self::$_instances[ $classname ])) {
self::createInstance($classname, $arguments);
}
$instance = self::$_instances[ $classname ];
return $instance;
} | Static object getter: creation of an instance from the class name passed in first argument
@param string $classname The classname to create object from
@param any You can define as many parameters as wanted, they will be passed to
the `__construct` or `init` methods
@return object This may return an instance of an object | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Abstracts/AbstractSingleton.php#L106-L115 |
atelierspierrot/patterns | src/Patterns/Abstracts/AbstractSingleton.php | AbstractSingleton.createInstance | private static function createInstance($classname, array $arguments = array())
{
$reflection_obj = new ReflectionClass($classname);
if ($reflection_obj->getMethod('__construct')->isPublic()) {
self::$_instances[ $classname ] = call_user_func_array(array($reflection_obj, 'newInstance'), $arguments);
if (
method_exists(self::$_instances[ $classname ], 'init') &&
is_callable(array(self::$_instances[ $classname ], 'init'))
) {
self::$_instances[ $classname ]->init();
}
} else {
self::$_instances[ $classname ] = new $classname;
if (
method_exists(self::$_instances[ $classname ], 'init') &&
is_callable(array(self::$_instances[ $classname ], 'init'))
) {
call_user_func_array(array(self::$_instances[ $classname ], 'init'), $arguments);
}
}
} | php | private static function createInstance($classname, array $arguments = array())
{
$reflection_obj = new ReflectionClass($classname);
if ($reflection_obj->getMethod('__construct')->isPublic()) {
self::$_instances[ $classname ] = call_user_func_array(array($reflection_obj, 'newInstance'), $arguments);
if (
method_exists(self::$_instances[ $classname ], 'init') &&
is_callable(array(self::$_instances[ $classname ], 'init'))
) {
self::$_instances[ $classname ]->init();
}
} else {
self::$_instances[ $classname ] = new $classname;
if (
method_exists(self::$_instances[ $classname ], 'init') &&
is_callable(array(self::$_instances[ $classname ], 'init'))
) {
call_user_func_array(array(self::$_instances[ $classname ], 'init'), $arguments);
}
}
} | Real object instances creation
@param string $classname The classname to create object from
@param array $arguments The arguments to pass to the `__construct` or `init` method
@return void | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Abstracts/AbstractSingleton.php#L124-L144 |
mlocati/concrete5-translation-library | src/Parser/DynamicItem/AttributeKey.php | AttributeKey.parseManual | public function parseManual(\Gettext\Translations $translations, $concrete5version)
{
if (class_exists('\AttributeKeyCategory', true) && class_exists('\AttributeKey', true)) {
foreach (\AttributeKeyCategory::getList() as $akc) {
foreach (\AttributeKey::getList($akc->getAttributeKeyCategoryHandle()) as $ak) {
$this->addTranslation($translations, $ak->getAttributeKeyName(), 'AttributeKeyName');
}
}
}
} | php | public function parseManual(\Gettext\Translations $translations, $concrete5version)
{
if (class_exists('\AttributeKeyCategory', true) && class_exists('\AttributeKey', true)) {
foreach (\AttributeKeyCategory::getList() as $akc) {
foreach (\AttributeKey::getList($akc->getAttributeKeyCategoryHandle()) as $ak) {
$this->addTranslation($translations, $ak->getAttributeKeyName(), 'AttributeKeyName');
}
}
}
} | {@inheritdoc}
@see \C5TL\Parser\DynamicItem\DynamicItem::parseManual() | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser/DynamicItem/AttributeKey.php#L35-L44 |
harp-orm/harp | src/Rel/AbstractRel.php | AbstractRel.linkModels | public function linkModels(Models $models, Models $foreign, Closure $yield)
{
foreach ($models as $model) {
$linked = [];
foreach ($foreign as $foreignModel) {
if ($this->areLinked($model, $foreignModel)) {
$linked []= $foreignModel;
}
}
$link = $this->newLinkFrom($model, $linked);
$yield($link);
}
} | php | public function linkModels(Models $models, Models $foreign, Closure $yield)
{
foreach ($models as $model) {
$linked = [];
foreach ($foreign as $foreignModel) {
if ($this->areLinked($model, $foreignModel)) {
$linked []= $foreignModel;
}
}
$link = $this->newLinkFrom($model, $linked);
$yield($link);
}
} | Iterate models and foreign models one by one and and assign links based on the areLinked method
Yeild the resulted links one by one for further processing.
@param Models $models
@param Models $foreign
@param Closure $yield call for each link | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Rel/AbstractRel.php#L165-L181 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Bundle/Form/Extension/ThemeExtension.php | ThemeExtension.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefault('synapse_form_options', array());
$resolver->setDefined(array('synapse_theme'));
$resolver->setNormalizer('synapse_theme', function (Options $options, $value) {
switch (true) {
case empty($value):
return $value;
case $value instanceof Theme:
return $value;
default:
if (!$theme = $this->themeLoader->retrieveByName($value)) {
throw new InvalidThemeException(sprintf(
'Theme "%s" not registered. Only %s are, check your configuration.',
$value,
$this->themeLoader->retrieveAll()->display('name')
));
}
return $theme;
}
});
} | php | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefault('synapse_form_options', array());
$resolver->setDefined(array('synapse_theme'));
$resolver->setNormalizer('synapse_theme', function (Options $options, $value) {
switch (true) {
case empty($value):
return $value;
case $value instanceof Theme:
return $value;
default:
if (!$theme = $this->themeLoader->retrieveByName($value)) {
throw new InvalidThemeException(sprintf(
'Theme "%s" not registered. Only %s are, check your configuration.',
$value,
$this->themeLoader->retrieveAll()->display('name')
));
}
return $theme;
}
});
} | {@inheritdoc}
Using loaders as callback normalizer / default don't cause loader hydration
while synapse form isn't activated : perf matters ! | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Form/Extension/ThemeExtension.php#L86-L111 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Bundle/Form/Extension/ThemeExtension.php | ThemeExtension.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
if (empty($options['synapse_theme'])) {
return;
}
$builder
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($builder, $options) {
$content = $event->getData();
if (!$content instanceof ContentInterface) {
throw new \InvalidArgumentException(sprintf(
'Synapse forms only supports ContentInterfaces as data, "%s" given.',
is_object($content) ? get_class($content) : gettype($content)
));
}
$event->getForm()->add('synapse', ThemeType::class, array_replace_recursive(
array('mapped' => false),
$options['synapse_form_options'],
array(
'compound' => true,
'auto_initialize' => false,
'theme' => $options['synapse_theme'],
'content' => $this->contentResolver->resolve($content),
)
));
}, -255)
;
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
if (empty($options['synapse_theme'])) {
return;
}
$builder
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($builder, $options) {
$content = $event->getData();
if (!$content instanceof ContentInterface) {
throw new \InvalidArgumentException(sprintf(
'Synapse forms only supports ContentInterfaces as data, "%s" given.',
is_object($content) ? get_class($content) : gettype($content)
));
}
$event->getForm()->add('synapse', ThemeType::class, array_replace_recursive(
array('mapped' => false),
$options['synapse_form_options'],
array(
'compound' => true,
'auto_initialize' => false,
'theme' => $options['synapse_theme'],
'content' => $this->contentResolver->resolve($content),
)
));
}, -255)
;
} | {@inheritdoc} | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Form/Extension/ThemeExtension.php#L116-L143 |
DeCarvalhoBruno/lti-wp-google | src/Google/Auth/OAuth2.php | Google_Auth_OAuth2.verifyIdToken | public function verifyIdToken($id_token = null, $audience = null)
{
if (!$id_token) {
$id_token = $this->token['id_token'];
}
$certs = $this->getFederatedSignonCerts();
if (!$audience) {
$audience = $this->client->getClassConfig($this, 'client_id');
}
return $this->verifySignedJwtWithCerts($id_token, $certs, $audience, self::OAUTH2_ISSUER);
} | php | public function verifyIdToken($id_token = null, $audience = null)
{
if (!$id_token) {
$id_token = $this->token['id_token'];
}
$certs = $this->getFederatedSignonCerts();
if (!$audience) {
$audience = $this->client->getClassConfig($this, 'client_id');
}
return $this->verifySignedJwtWithCerts($id_token, $certs, $audience, self::OAUTH2_ISSUER);
} | Verifies an id token and returns the authenticated apiLoginTicket.
Throws an exception if the id token is not valid.
The audience parameter can be used to control which id tokens are
accepted. By default, the id token must have been issued to this OAuth2 client.
@param $id_token
@param $audience
@return Google_Auth_LoginTicket | https://github.com/DeCarvalhoBruno/lti-wp-google/blob/3a013cdf307df61018da96a075217194004311c6/src/Google/Auth/OAuth2.php#L475-L486 |
praxisnetau/silverware-navigation | src/Model/LinkHolder.php | LinkHolder.getCMSFields | public function getCMSFields()
{
// Obtain Field Objects (from parent):
$fields = parent::getCMSFields();
// Create Main Fields:
$fields->addFieldsToTab(
'Root.Main',
[
HTMLEditorField::create(
'HeaderContent',
$this->fieldLabel('HeaderContent')
)->setRows(10),
HTMLEditorField::create(
'FooterContent',
$this->fieldLabel('FooterContent')
)->setRows(10)
]
);
// Insert Links Tab:
$fields->insertAfter(
Tab::create(
'Links',
$this->fieldLabel('Links')
),
'Main'
);
// Add Links Fields:
$fields->addFieldsToTab(
'Root.Links',
[
DropdownField::create(
'LinkMode',
$this->fieldLabel('LinkMode'),
$this->getLinkModeOptions()
),
PageMultiselectField::create(
'LinkedPages',
$this->fieldLabel('LinkedPages')
)
]
);
// Create Options Fields:
$fields->addFieldToTab(
'Root.Options',
FieldSection::create(
'NavigationOptions',
$this->fieldLabel('NavigationOptions'),
[
DropdownField::create(
'SortBy',
$this->fieldLabel('SortBy'),
$this->getSortByOptions()
),
CheckboxField::create(
'ShowIcons',
$this->fieldLabel('ShowIcons')
)
]
)
);
// Answer Field Objects:
return $fields;
} | php | public function getCMSFields()
{
// Obtain Field Objects (from parent):
$fields = parent::getCMSFields();
// Create Main Fields:
$fields->addFieldsToTab(
'Root.Main',
[
HTMLEditorField::create(
'HeaderContent',
$this->fieldLabel('HeaderContent')
)->setRows(10),
HTMLEditorField::create(
'FooterContent',
$this->fieldLabel('FooterContent')
)->setRows(10)
]
);
// Insert Links Tab:
$fields->insertAfter(
Tab::create(
'Links',
$this->fieldLabel('Links')
),
'Main'
);
// Add Links Fields:
$fields->addFieldsToTab(
'Root.Links',
[
DropdownField::create(
'LinkMode',
$this->fieldLabel('LinkMode'),
$this->getLinkModeOptions()
),
PageMultiselectField::create(
'LinkedPages',
$this->fieldLabel('LinkedPages')
)
]
);
// Create Options Fields:
$fields->addFieldToTab(
'Root.Options',
FieldSection::create(
'NavigationOptions',
$this->fieldLabel('NavigationOptions'),
[
DropdownField::create(
'SortBy',
$this->fieldLabel('SortBy'),
$this->getSortByOptions()
),
CheckboxField::create(
'ShowIcons',
$this->fieldLabel('ShowIcons')
)
]
)
);
// Answer Field Objects:
return $fields;
} | Answers a list of field objects for the CMS interface.
@return FieldList | https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Model/LinkHolder.php#L167-L240 |
praxisnetau/silverware-navigation | src/Model/LinkHolder.php | LinkHolder.getEnabledLinks | public function getEnabledLinks()
{
switch ($this->LinkMode) {
case self::MODE_PAGES:
$links = ArrayList::create();
foreach ($this->LinkedPages() as $page) {
$link = $page->toLink();
$link->setParent($this);
$links->push($link);
}
break;
default:
$links = $this->getLinks()->filterByCallback(function ($link) {
return $link->isEnabled();
});
}
return $links->sort($this->getSortOrder());
} | php | public function getEnabledLinks()
{
switch ($this->LinkMode) {
case self::MODE_PAGES:
$links = ArrayList::create();
foreach ($this->LinkedPages() as $page) {
$link = $page->toLink();
$link->setParent($this);
$links->push($link);
}
break;
default:
$links = $this->getLinks()->filterByCallback(function ($link) {
return $link->isEnabled();
});
}
return $links->sort($this->getSortOrder());
} | Answers a list of the enabled links within the receiver.
@return ArrayList | https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Model/LinkHolder.php#L316-L341 |
PlatoCreative/silverstripe-sections | code/sections/FormSection.php | FormSection.getCMSFields | public function getCMSFields()
{
$fields = parent::getCMSFields();
$fields->addFieldsToTab(
"Root.Main",
array(
DropdownField::create(
'FormPageID',
'Select a page',
UserDefinedForm::get()->map('ID', 'Title')
)
)
);
$this->extend('updateCMSFields', $fields);
return $fields;
} | php | public function getCMSFields()
{
$fields = parent::getCMSFields();
$fields->addFieldsToTab(
"Root.Main",
array(
DropdownField::create(
'FormPageID',
'Select a page',
UserDefinedForm::get()->map('ID', 'Title')
)
)
);
$this->extend('updateCMSFields', $fields);
return $fields;
} | CMS Fields
@return FieldList | https://github.com/PlatoCreative/silverstripe-sections/blob/54c96146ea8cc625b00ee009753539658f10d01a/code/sections/FormSection.php#L34-L51 |
as3io/symfony-data-importer | src/Import/Source/Dummy.php | Dummy.retrieve | public function retrieve($from, $criteria, array $fields = [], array $sort = [], $limit = 200, $skip = 0)
{
$docs = [];
for ($i=0; $i < $limit; $i++) {
$docs[] = $this->createDoc();
}
return $docs;
// return array_fill(0, $limit, $this->createDoc());
} | php | public function retrieve($from, $criteria, array $fields = [], array $sort = [], $limit = 200, $skip = 0)
{
$docs = [];
for ($i=0; $i < $limit; $i++) {
$docs[] = $this->createDoc();
}
return $docs;
// return array_fill(0, $limit, $this->createDoc());
} | {@inheritdoc} | https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Import/Source/Dummy.php#L37-L45 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/CssFile.php | CssFile.addIfExists | public function addIfExists($file_path, $media = 'screen', $condition = null)
{
$_fp = $this->__template->findAsset($file_path);
if ($_fp || \AssetsManager\Loader::isUrl($file_path)) {
return $this->add($file_path, $media, $condition);
}
return $this;
} | php | public function addIfExists($file_path, $media = 'screen', $condition = null)
{
$_fp = $this->__template->findAsset($file_path);
if ($_fp || \AssetsManager\Loader::isUrl($file_path)) {
return $this->add($file_path, $media, $condition);
}
return $this;
} | Add a CSS file in CSS stack if it exists
@param string $file_path The new CSS path
@param string $media The media type for the CSS file (default is "screen")
@param string|null $condition Define a condition (for IE) for this stylesheet
@return self | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/CssFile.php#L70-L77 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/CssFile.php | CssFile.add | public function add($file_path, $media = 'screen', $condition = null)
{
$_fp = $this->__template->findAsset($file_path);
if ($_fp || \AssetsManager\Loader::isUrl($file_path)) {
$this->registry->addEntry(array(
'file'=>$_fp, 'media'=>$media, 'condition'=>$condition
), 'css_files');
} else {
throw new \InvalidArgumentException(
sprintf('CSS file "%s" not found!', $file_path)
);
}
return $this;
} | php | public function add($file_path, $media = 'screen', $condition = null)
{
$_fp = $this->__template->findAsset($file_path);
if ($_fp || \AssetsManager\Loader::isUrl($file_path)) {
$this->registry->addEntry(array(
'file'=>$_fp, 'media'=>$media, 'condition'=>$condition
), 'css_files');
} else {
throw new \InvalidArgumentException(
sprintf('CSS file "%s" not found!', $file_path)
);
}
return $this;
} | Add a CSS file in CSS stack
@param string $file_path The new CSS path
@param string $media The media type for the CSS file (default is "screen")
@param string|null $condition Define a condition (for IE) for this stylesheet
@return self
@throws \InvalidArgumentException if the path doesn't exist | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/CssFile.php#L88-L101 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/CssFile.php | CssFile.set | public function set(array $files)
{
if (!empty($files)) {
foreach ($files as $_file) {
if (is_array($_file) && isset($_file['file'])) {
$this->add(
$_file['file'],
isset($_file['media']) ? $_file['media'] : '',
isset($_file['condition']) ? $_file['condition'] : null
);
} elseif (is_string($_file)) {
$this->add($_file);
}
}
}
return $this;
} | php | public function set(array $files)
{
if (!empty($files)) {
foreach ($files as $_file) {
if (is_array($_file) && isset($_file['file'])) {
$this->add(
$_file['file'],
isset($_file['media']) ? $_file['media'] : '',
isset($_file['condition']) ? $_file['condition'] : null
);
} elseif (is_string($_file)) {
$this->add($_file);
}
}
}
return $this;
} | Set a full CSS stack
@param array $files An array of CSS files paths
@return self
@see self::add() | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/CssFile.php#L110-L126 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/CssFile.php | CssFile.merge | public function merge()
{
$css_files = $this->cleanStack($this->get(), 'file');
$organized_css = array( 'rest'=>array() );
foreach ($css_files as $_file) {
if (!empty($_file['media'])) {
if (!isset($organized_css[ $_file['media'] ])) {
$organized_css[ $_file['media'] ] = array();
}
$organized_css[ $_file['media'] ][] = $_file;
} else {
$organized_css['rest'][] = $_file;
}
}
foreach ($organized_css as $media=>$stack) {
$cleaned_stack = $this->extractFromStack($stack, 'file');
if (!empty($cleaned_stack)) {
$this->addMerged(
$this->mergeStack($cleaned_stack), $media=='rest' ? 'screen' : $media
);
}
}
return $this;
} | php | public function merge()
{
$css_files = $this->cleanStack($this->get(), 'file');
$organized_css = array( 'rest'=>array() );
foreach ($css_files as $_file) {
if (!empty($_file['media'])) {
if (!isset($organized_css[ $_file['media'] ])) {
$organized_css[ $_file['media'] ] = array();
}
$organized_css[ $_file['media'] ][] = $_file;
} else {
$organized_css['rest'][] = $_file;
}
}
foreach ($organized_css as $media=>$stack) {
$cleaned_stack = $this->extractFromStack($stack, 'file');
if (!empty($cleaned_stack)) {
$this->addMerged(
$this->mergeStack($cleaned_stack), $media=='rest' ? 'screen' : $media
);
}
}
return $this;
} | Merge the files if possible and loads them in files_merged stack
@return self Must return the object itself for method chaining | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/CssFile.php#L174-L200 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/CssFile.php | CssFile.addMerged | public function addMerged($file_path, $media = 'screen')
{
$_fp = $this->__template->findAsset($file_path);
if ($_fp || \AssetsManager\Loader::isUrl($file_path)) {
$this->registry->addEntry(array(
'file'=>$_fp, 'media'=>$media
), 'css_merged_files');
} else {
throw new \InvalidArgumentException(
sprintf('CSS merged file "%s" not found!', $file_path)
);
}
return $this;
} | php | public function addMerged($file_path, $media = 'screen')
{
$_fp = $this->__template->findAsset($file_path);
if ($_fp || \AssetsManager\Loader::isUrl($file_path)) {
$this->registry->addEntry(array(
'file'=>$_fp, 'media'=>$media
), 'css_merged_files');
} else {
throw new \InvalidArgumentException(
sprintf('CSS merged file "%s" not found!', $file_path)
);
}
return $this;
} | Add an merged file
@param string $file_path The new CSS path
@param string $media The media type for the CSS file (default is "screen")
@return self
@throws \InvalidArgumentException if the path doesn't exist | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/CssFile.php#L210-L223 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/CssFile.php | CssFile.setMerged | public function setMerged(array $files)
{
if (!empty($files)) {
foreach ($files as $_file) {
if (is_array($_file) && isset($_file['file'])) {
if (isset($_file['media'])) {
$this->add($_file['file'], $_file['media']);
} else {
$this->add($_file['file']);
}
} elseif (is_string($_file)) {
$this->add($_file);
}
}
}
return $this;
} | php | public function setMerged(array $files)
{
if (!empty($files)) {
foreach ($files as $_file) {
if (is_array($_file) && isset($_file['file'])) {
if (isset($_file['media'])) {
$this->add($_file['file'], $_file['media']);
} else {
$this->add($_file['file']);
}
} elseif (is_string($_file)) {
$this->add($_file);
}
}
}
return $this;
} | Set a stack of merged files
@param array $files An array of CSS files paths
@return self
@see self::add() | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/CssFile.php#L232-L248 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/CssFile.php | CssFile.minify | public function minify()
{
$css_files = $this->cleanStack($this->get(), 'file');
$organized_css = array('rest'=>array());
foreach ($css_files as $_file) {
if (!empty($_file['media'])) {
if (!isset($organized_css[ $_file['media'] ])) {
$organized_css[ $_file['media'] ] = array();
}
$organized_css[ $_file['media'] ][] = $_file;
} else {
$organized_css['rest'][] = $_file;
}
}
foreach ($organized_css as $media=>$stack) {
$cleaned_stack = $this->extractFromStack($stack, 'file');
if (!empty($cleaned_stack)) {
$this->addMinified(
$this->minifyStack($cleaned_stack), $media=='rest' ? 'screen' : $media
);
}
}
return $this;
} | php | public function minify()
{
$css_files = $this->cleanStack($this->get(), 'file');
$organized_css = array('rest'=>array());
foreach ($css_files as $_file) {
if (!empty($_file['media'])) {
if (!isset($organized_css[ $_file['media'] ])) {
$organized_css[ $_file['media'] ] = array();
}
$organized_css[ $_file['media'] ][] = $_file;
} else {
$organized_css['rest'][] = $_file;
}
}
foreach ($organized_css as $media=>$stack) {
$cleaned_stack = $this->extractFromStack($stack, 'file');
if (!empty($cleaned_stack)) {
$this->addMinified(
$this->minifyStack($cleaned_stack), $media=='rest' ? 'screen' : $media
);
}
}
return $this;
} | Minify the files if possible and loads them in files_minified stack
@return self Must return the object itself for method chaining | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/CssFile.php#L288-L314 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/CssFile.php | CssFile.writeMinified | public function writeMinified($mask = '%s')
{
$str='';
foreach ($this->cleanStack($this->getMinified(), 'file') as $entry) {
$tag_attrs = array(
'rel'=>'stylesheet',
'type'=>'text/css',
'href'=>$entry['file']
);
if (isset($entry['media']) && !empty($entry['media']) && $entry['media']!='screen') {
$tag_attrs['media'] = $entry['media'];
}
$str .= sprintf($mask, Html::writeHtmlTag('link', null, $tag_attrs, true));
}
return $str;
} | php | public function writeMinified($mask = '%s')
{
$str='';
foreach ($this->cleanStack($this->getMinified(), 'file') as $entry) {
$tag_attrs = array(
'rel'=>'stylesheet',
'type'=>'text/css',
'href'=>$entry['file']
);
if (isset($entry['media']) && !empty($entry['media']) && $entry['media']!='screen') {
$tag_attrs['media'] = $entry['media'];
}
$str .= sprintf($mask, Html::writeHtmlTag('link', null, $tag_attrs, true));
}
return $str;
} | Write minified versions of the files stack in the cache directory
@param string $mask A mask to write each line via "sprintf()"
@return string The string to display fot this template object | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/CssFile.php#L380-L395 |
antaresproject/sample_module | src/Processor/ModuleProcessor.php | ModuleProcessor.create | public function create()
{
$model = new ModuleRow();
$form = $this->form($model);
if (app('request')->isMethod('post')) {
if (!$form->isValid()) {
return ['errors' => $form->getMessageBag()];
}
}
return ['form' => $form];
} | php | public function create()
{
$model = new ModuleRow();
$form = $this->form($model);
if (app('request')->isMethod('post')) {
if (!$form->isValid()) {
return ['errors' => $form->getMessageBag()];
}
}
return ['form' => $form];
} | Obsługa formularza
@return array | https://github.com/antaresproject/sample_module/blob/aceab14f392c25e32729018518e9d6b4e6fe23db/src/Processor/ModuleProcessor.php#L83-L93 |
antaresproject/sample_module | src/Processor/ModuleProcessor.php | ModuleProcessor.form | protected function form(Model $model)
{
$this->breadcrumb->onItem($model);
return app('antares.form')->of('awesone-module-form', function(FormGrid $form) use($model) {
$form->name('My Awesome Module Form');
$form->resourced('antares::sample_module/index', $model);
$form->fieldset(function (Fieldset $fieldset) use($model) {
$fieldset->legend('Fieldset');
if (!auth()->user()->hasRoles('member')) {
$fieldset->control('select', 'user')
->label(trans('antares/sample_module::form.user_select'))
->options(function() {
return User::members()
->select([DB::raw('concat(firstname," ",lastname) as name'), 'id'])
->orderBy('firstname', 'asc')
->orderBy('lastname', 'desc')
->get()
->map(function($option) {
return ['id' => $option->id, 'title' => '#' . $option->id . ' ' . $option->name];
})->pluck('title', 'id');
})
->attributes(['data-selectar--search' => true, 'data-placeholder' => 'testowanie'])
->wrapper(['class' => 'w300'])
->value($model->user_id);
}
$fieldset->control('input:text', 'name')
->label(trans('antares/sample_module::form.name'))
->wrapper(['class' => 'w300']);
$fieldset->control('select', 'field_1')
->label(trans('antares/sample_module::form.field_1'))
->options(self::getOptions())
->wrapper(['class' => 'w200']);
$fieldset->control('input:checkbox', 'field_2')
->label(trans('antares/sample_module::form.field_2'))
->value(1)
->checked($model->exists ? array_get($model->value, 'field_2', false) : false);
$fieldset->control('button', 'cancel')
->field(function() {
return app('html')->link(handles("antares::sample_module/index"), trans('antares/foundation::label.cancel'), ['class' => 'btn btn--md btn--default mdl-button mdl-js-button']);
});
$fieldset->control('button', 'button')
->attributes(['type' => 'submit', 'class' => 'btn btn-primary'])
->value(trans('antares/foundation::label.save_changes'));
});
$form->ajaxable()->rules(['name' => 'required']);
});
} | php | protected function form(Model $model)
{
$this->breadcrumb->onItem($model);
return app('antares.form')->of('awesone-module-form', function(FormGrid $form) use($model) {
$form->name('My Awesome Module Form');
$form->resourced('antares::sample_module/index', $model);
$form->fieldset(function (Fieldset $fieldset) use($model) {
$fieldset->legend('Fieldset');
if (!auth()->user()->hasRoles('member')) {
$fieldset->control('select', 'user')
->label(trans('antares/sample_module::form.user_select'))
->options(function() {
return User::members()
->select([DB::raw('concat(firstname," ",lastname) as name'), 'id'])
->orderBy('firstname', 'asc')
->orderBy('lastname', 'desc')
->get()
->map(function($option) {
return ['id' => $option->id, 'title' => '#' . $option->id . ' ' . $option->name];
})->pluck('title', 'id');
})
->attributes(['data-selectar--search' => true, 'data-placeholder' => 'testowanie'])
->wrapper(['class' => 'w300'])
->value($model->user_id);
}
$fieldset->control('input:text', 'name')
->label(trans('antares/sample_module::form.name'))
->wrapper(['class' => 'w300']);
$fieldset->control('select', 'field_1')
->label(trans('antares/sample_module::form.field_1'))
->options(self::getOptions())
->wrapper(['class' => 'w200']);
$fieldset->control('input:checkbox', 'field_2')
->label(trans('antares/sample_module::form.field_2'))
->value(1)
->checked($model->exists ? array_get($model->value, 'field_2', false) : false);
$fieldset->control('button', 'cancel')
->field(function() {
return app('html')->link(handles("antares::sample_module/index"), trans('antares/foundation::label.cancel'), ['class' => 'btn btn--md btn--default mdl-button mdl-js-button']);
});
$fieldset->control('button', 'button')
->attributes(['type' => 'submit', 'class' => 'btn btn-primary'])
->value(trans('antares/foundation::label.save_changes'));
});
$form->ajaxable()->rules(['name' => 'required']);
});
} | Generowanie nowego obiektu formularza
@param Model $model
@return \Antares\Html\Form\FormBuilder | https://github.com/antaresproject/sample_module/blob/aceab14f392c25e32729018518e9d6b4e6fe23db/src/Processor/ModuleProcessor.php#L101-L156 |
antaresproject/sample_module | src/Processor/ModuleProcessor.php | ModuleProcessor.store | public function store()
{
$input = Input::all();
$user = auth()->user();
$attributes = [
'user_id' => $user->hasRoles('member') ? $user->id : array_get($input, 'user'),
'name' => array_get($input, 'name'),
'value' => array_only($input, ['field_1', 'field_2'])
];
$model = new ModuleRow($attributes);
$form = $this->form($model);
if (!$form->isValid()) {
return redirect_with_errors(handles('antares::sample_module/index/create'), $form->getMessageBag());
}
if (!$model->save()) {
event('notifications.item_has_not_been_created', ['variables' => ['user' => $user, 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.save_error'), 'error');
}
event('notifications.item_has_been_created', ['variables' => ['user' => $user, 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.save_success'), 'success');
} | php | public function store()
{
$input = Input::all();
$user = auth()->user();
$attributes = [
'user_id' => $user->hasRoles('member') ? $user->id : array_get($input, 'user'),
'name' => array_get($input, 'name'),
'value' => array_only($input, ['field_1', 'field_2'])
];
$model = new ModuleRow($attributes);
$form = $this->form($model);
if (!$form->isValid()) {
return redirect_with_errors(handles('antares::sample_module/index/create'), $form->getMessageBag());
}
if (!$model->save()) {
event('notifications.item_has_not_been_created', ['variables' => ['user' => $user, 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.save_error'), 'error');
}
event('notifications.item_has_been_created', ['variables' => ['user' => $user, 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.save_success'), 'success');
} | When stores form fields in database
@return \Illuminate\Http\RedirectResponse | https://github.com/antaresproject/sample_module/blob/aceab14f392c25e32729018518e9d6b4e6fe23db/src/Processor/ModuleProcessor.php#L173-L194 |
antaresproject/sample_module | src/Processor/ModuleProcessor.php | ModuleProcessor.update | public function update($id)
{
$model = ModuleRow::withoutGlobalScopes()->findOrFail($id);
if (!request()->isMethod('put')) {
$form = $this->form($model);
} else {
$input = Input::all();
$user = auth()->user();
if (!$user->hasRoles('member')) {
$model->user_id = array_get($input, 'user');
}
$model->name = array_get($input, 'name');
$model->value = array_only($input, ['field_1', 'field_2']);
$form = $this->form($model);
if (!$form->isValid()) {
return redirect_with_errors(handles('antares::sample_module/index/' . $id . '/edit'), $form->getMessageBag());
}
if (!$model->save()) {
event('notifications.item_has_not_been_updated', ['variables' => ['user' => user(), 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.update_error'), 'error');
}
event('notifications.item_has_been_updated', ['variables' => ['user' => user(), 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.update_success'), 'success');
}
return view('antares/sample_module::admin.module.create', ['form' => $form]);
} | php | public function update($id)
{
$model = ModuleRow::withoutGlobalScopes()->findOrFail($id);
if (!request()->isMethod('put')) {
$form = $this->form($model);
} else {
$input = Input::all();
$user = auth()->user();
if (!$user->hasRoles('member')) {
$model->user_id = array_get($input, 'user');
}
$model->name = array_get($input, 'name');
$model->value = array_only($input, ['field_1', 'field_2']);
$form = $this->form($model);
if (!$form->isValid()) {
return redirect_with_errors(handles('antares::sample_module/index/' . $id . '/edit'), $form->getMessageBag());
}
if (!$model->save()) {
event('notifications.item_has_not_been_updated', ['variables' => ['user' => user(), 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.update_error'), 'error');
}
event('notifications.item_has_been_updated', ['variables' => ['user' => user(), 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.update_success'), 'success');
}
return view('antares/sample_module::admin.module.create', ['form' => $form]);
} | When updates form fields in database
@param mixes $id
@return \Illuminate\Http\RedirectResponse | https://github.com/antaresproject/sample_module/blob/aceab14f392c25e32729018518e9d6b4e6fe23db/src/Processor/ModuleProcessor.php#L202-L233 |
antaresproject/sample_module | src/Processor/ModuleProcessor.php | ModuleProcessor.delete | public function delete($id)
{
$builder = ModuleRow::withoutGlobalScopes();
if (auth()->user()->hasRoles('member')) {
$builder->where(['user_id' => auth()->user()->id]);
}
$model = $builder->findOrFail($id);
$name = $model->name;
if ($model->delete()) {
event('notifications.item_has_been_deleted', ['variables' => ['user' => user(), 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.item_has_been_deleted', ['name' => $name]), 'success');
}
event('notifications.item_has_not_been_deleted', ['variables' => ['user' => user(), 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.item_has_not_been_deleted', ['name' => $name]), 'error');
} | php | public function delete($id)
{
$builder = ModuleRow::withoutGlobalScopes();
if (auth()->user()->hasRoles('member')) {
$builder->where(['user_id' => auth()->user()->id]);
}
$model = $builder->findOrFail($id);
$name = $model->name;
if ($model->delete()) {
event('notifications.item_has_been_deleted', ['variables' => ['user' => user(), 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.item_has_been_deleted', ['name' => $name]), 'success');
}
event('notifications.item_has_not_been_deleted', ['variables' => ['user' => user(), 'item' => $model]]);
return redirect_with_message(handles('antares::sample_module/index'), trans('antares/sample_module::messages.item_has_not_been_deleted', ['name' => $name]), 'error');
} | When deletes item
@param mixed $id
@return \Illuminate\Http\RedirectResponse | https://github.com/antaresproject/sample_module/blob/aceab14f392c25e32729018518e9d6b4e6fe23db/src/Processor/ModuleProcessor.php#L241-L255 |
kouks/laravel-casters | src/Casters/Caster.php | Caster.cast | public function cast($model)
{
if ($model instanceof Collection) {
return $model->map([$this, 'cast'])->toArray();
}
if (empty($model)) {
return;
}
$transformed = [];
foreach ($this->castRules() as $old => $desired) {
$this->resolveCast($old, $desired, $model, $transformed);
}
return $transformed;
} | php | public function cast($model)
{
if ($model instanceof Collection) {
return $model->map([$this, 'cast'])->toArray();
}
if (empty($model)) {
return;
}
$transformed = [];
foreach ($this->castRules() as $old => $desired) {
$this->resolveCast($old, $desired, $model, $transformed);
}
return $transformed;
} | Casts collection fields.
@param mixed $model
@return array | https://github.com/kouks/laravel-casters/blob/6b5ada1147b658cf2866a9e9573b66ff699edbbf/src/Casters/Caster.php#L35-L52 |
kouks/laravel-casters | src/Casters/Caster.php | Caster.resolveCast | private function resolveCast($old, $desired, Model $model, &$transformed)
{
if ($desired instanceof Closure) {
return $transformed[$old] = call_user_func($desired, $model);
}
if (is_string($desired) && strpos($desired, $this->functionSign) !== false) {
return $transformed[$old] = call_user_func([$this, substr($desired, 1)], $model);
}
if (is_string($desired) && strpos($desired, $this->querySign) !== false) {
return $this->parse($old, substr($desired, 1), $model, $transformed);
}
if (is_string($old)) {
return $transformed[$desired] = $model->$old;
}
return $transformed[$desired] = $model->$desired;
} | php | private function resolveCast($old, $desired, Model $model, &$transformed)
{
if ($desired instanceof Closure) {
return $transformed[$old] = call_user_func($desired, $model);
}
if (is_string($desired) && strpos($desired, $this->functionSign) !== false) {
return $transformed[$old] = call_user_func([$this, substr($desired, 1)], $model);
}
if (is_string($desired) && strpos($desired, $this->querySign) !== false) {
return $this->parse($old, substr($desired, 1), $model, $transformed);
}
if (is_string($old)) {
return $transformed[$desired] = $model->$old;
}
return $transformed[$desired] = $model->$desired;
} | Resolves casts based on supplied array of arguments.
@param string $old
@param string|Closure $desired
@param \Illuminate\Database\Eloquent\Model $model
@param array &$transformed
@return array | https://github.com/kouks/laravel-casters/blob/6b5ada1147b658cf2866a9e9573b66ff699edbbf/src/Casters/Caster.php#L63-L82 |
SpoonX/SxBootstrap | src/SxBootstrap/View/Helper/Bootstrap/Tabs.php | Tabs.render | protected function render()
{
if (null === $this->active) {
$this->setActive(key($this->tabs));
}
$tabs = new ViewModel;
$tabs->tabs = $this->tabs;
$tabs->setTemplate('sxbootstrap/tabs/tabs');
return $this->getView()->render($tabs);
} | php | protected function render()
{
if (null === $this->active) {
$this->setActive(key($this->tabs));
}
$tabs = new ViewModel;
$tabs->tabs = $this->tabs;
$tabs->setTemplate('sxbootstrap/tabs/tabs');
return $this->getView()->render($tabs);
} | Renders the tabs and returns the markup.
@return string | https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Tabs.php#L69-L81 |
SpoonX/SxBootstrap | src/SxBootstrap/View/Helper/Bootstrap/Tabs.php | Tabs.setActive | public function setActive($tabId = null)
{
$tabId = is_null($tabId) ? $this->getTabId(true) : $tabId;
if (empty($this->tabs[$tabId])) {
throw new Exception\InvalidArgumentException('Invalid tab id supplied.');
}
if (null !== $this->active) {
$this->tabs[$this->active]['active'] = false;
}
$this->tabs[$tabId]['active'] = true;
$this->active = $tabId;
return $this;
} | php | public function setActive($tabId = null)
{
$tabId = is_null($tabId) ? $this->getTabId(true) : $tabId;
if (empty($this->tabs[$tabId])) {
throw new Exception\InvalidArgumentException('Invalid tab id supplied.');
}
if (null !== $this->active) {
$this->tabs[$this->active]['active'] = false;
}
$this->tabs[$tabId]['active'] = true;
$this->active = $tabId;
return $this;
} | Set the active tab. Falls back to last added tab when $tabId was not provided.
@param string $tabId The to-be-marked active tab's identifier.
@return Tabs
@throws Exception\InvalidArgumentException | https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Tabs.php#L91-L106 |
SpoonX/SxBootstrap | src/SxBootstrap/View/Helper/Bootstrap/Tabs.php | Tabs.add | public function add($label, $content = null, $tabId = null, $active = false)
{
$tabId = is_null($tabId) ? $this->getTabId() : $tabId;
$label = is_null($label) ? $tabId : $label;
$this->tabs[$tabId] = array (
'label' => $label,
'content' => $content,
'active' => $active,
);
return $this;
} | php | public function add($label, $content = null, $tabId = null, $active = false)
{
$tabId = is_null($tabId) ? $this->getTabId() : $tabId;
$label = is_null($label) ? $tabId : $label;
$this->tabs[$tabId] = array (
'label' => $label,
'content' => $content,
'active' => $active,
);
return $this;
} | Add a new tab.
@param string $label The label for the tab.
@param string $content The tab's content. Can be added later.
@param string $tabId The tab's id. Autogenerated when left empty.
@param boolean $active If this tab should be active.
@return Tabs Fluent interface | https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Tabs.php#L118-L130 |
SpoonX/SxBootstrap | src/SxBootstrap/View/Helper/Bootstrap/Tabs.php | Tabs.addContent | public function addContent($content, $tabId = null)
{
$tabId = is_null($tabId) ? $this->getTabId(true) : $tabId;
if (empty($this->tabs[$tabId])) {
throw new Exception\InvalidArgumentException('Invalid tab id supplied.');
}
$this->tabs[$tabId]['content'] .= $content;
} | php | public function addContent($content, $tabId = null)
{
$tabId = is_null($tabId) ? $this->getTabId(true) : $tabId;
if (empty($this->tabs[$tabId])) {
throw new Exception\InvalidArgumentException('Invalid tab id supplied.');
}
$this->tabs[$tabId]['content'] .= $content;
} | Add the content for tab $tabId. Falls back to last added tab when $tabId was not provided.
@param string $content The content to be added.
@param string $tabId The id of the tab you wish to add this content to.
@throws Exception\InvalidArgumentException | https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Tabs.php#L159-L168 |
SpoonX/SxBootstrap | src/SxBootstrap/View/Helper/Bootstrap/Tabs.php | Tabs.getTabId | protected function getTabId($current = false)
{
if (true === $current) {
return key($this->tabs);
}
$c = $this->tabCount++;
return $this->defaultTabIdentifier . $c;
} | php | protected function getTabId($current = false)
{
if (true === $current) {
return key($this->tabs);
}
$c = $this->tabCount++;
return $this->defaultTabIdentifier . $c;
} | Generate an id for a tab, or get the last added one.
@param boolean $current Whether or not to get the last added id.
@return string | https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Tabs.php#L177-L186 |
jawira/mini-getopt | src/MiniGetopt.php | MiniGetopt.addRequired | public function addRequired(string $short, string $long, string $description = '', string $placeholder = 'value')
{
$this->addOption(self::REQUIRED, $short, $long, $description, $placeholder);
return $this;
} | php | public function addRequired(string $short, string $long, string $description = '', string $placeholder = 'value')
{
$this->addOption(self::REQUIRED, $short, $long, $description, $placeholder);
return $this;
} | @param string $short
@param string $long
@param string $description
@param string $placeholder
@return $this
@throws \Jawira\MiniGetopt\MiniGetoptException | https://github.com/jawira/mini-getopt/blob/f9f35409a7cd72f37a0ec9dd6a34c091e4a22c41/src/MiniGetopt.php#L27-L31 |
jawira/mini-getopt | src/MiniGetopt.php | MiniGetopt.addOptional | public function addOptional(string $short, string $long, string $description = '', string $placeholder = 'value')
{
$this->addOption(self::OPTIONAL, $short, $long, $description, $placeholder);
return $this;
} | php | public function addOptional(string $short, string $long, string $description = '', string $placeholder = 'value')
{
$this->addOption(self::OPTIONAL, $short, $long, $description, $placeholder);
return $this;
} | @param string $short
@param string $long
@param string $description
@param string $placeholder
@return $this
@throws \Jawira\MiniGetopt\MiniGetoptException | https://github.com/jawira/mini-getopt/blob/f9f35409a7cd72f37a0ec9dd6a34c091e4a22c41/src/MiniGetopt.php#L42-L46 |
jawira/mini-getopt | src/MiniGetopt.php | MiniGetopt.addNoValue | public function addNoValue(string $short, string $long, string $description = '')
{
$this->addOption(self::NO_VALUE, $short, $long, $description, '');
return $this;
} | php | public function addNoValue(string $short, string $long, string $description = '')
{
$this->addOption(self::NO_VALUE, $short, $long, $description, '');
return $this;
} | @param string $short
@param string $long
@param string $description
@return $this
@throws \Jawira\MiniGetopt\MiniGetoptException | https://github.com/jawira/mini-getopt/blob/f9f35409a7cd72f37a0ec9dd6a34c091e4a22c41/src/MiniGetopt.php#L56-L60 |
jawira/mini-getopt | src/MiniGetopt.php | MiniGetopt.addOption | protected function addOption(string $type, string $short, string $long, string $description, string $placeholder)
{
$this->validateShortAndLong($short, $long);
$this->options[] = compact('type', 'short', 'long', 'description', 'placeholder');
return $this;
} | php | protected function addOption(string $type, string $short, string $long, string $description, string $placeholder)
{
$this->validateShortAndLong($short, $long);
$this->options[] = compact('type', 'short', 'long', 'description', 'placeholder');
return $this;
} | @param string $type
@param string $short
@param string $long
@param string $description
@param string $placeholder
@return $this
@throws \Jawira\MiniGetopt\MiniGetoptException | https://github.com/jawira/mini-getopt/blob/f9f35409a7cd72f37a0ec9dd6a34c091e4a22c41/src/MiniGetopt.php#L72-L78 |
jawira/mini-getopt | src/MiniGetopt.php | MiniGetopt.getOption | public function getOption(string $short, string $long, $default = null)
{
$this->validateShortAndLong($short, $long);
$getopt = $this->getopt();
if (array_key_exists($short, $getopt)) {
return $getopt[$short];
}
if (array_key_exists($long, $getopt)) {
return $getopt[$long];
}
return $default;
} | php | public function getOption(string $short, string $long, $default = null)
{
$this->validateShortAndLong($short, $long);
$getopt = $this->getopt();
if (array_key_exists($short, $getopt)) {
return $getopt[$short];
}
if (array_key_exists($long, $getopt)) {
return $getopt[$long];
}
return $default;
} | @param string $short
@param string $long
@param null $default
@return mixed
@throws \Jawira\MiniGetopt\MiniGetoptException | https://github.com/jawira/mini-getopt/blob/f9f35409a7cd72f37a0ec9dd6a34c091e4a22c41/src/MiniGetopt.php#L177-L189 |
jawira/mini-getopt | src/MiniGetopt.php | MiniGetopt.validateShortAndLong | protected function validateShortAndLong(string $short, string $long): self
{
if (!$this->validShort($short)) {
throw new MiniGetoptException("Short option '$short' should be one character long");
}
if (!$this->validLong($long)) {
throw new MiniGetoptException("Long option '$long' should be at least two characters long");
}
if ($this->emptyString($short) && $this->emptyString($long)) {
throw new MiniGetoptException("You should define at least short option or long option");
}
return $this;
} | php | protected function validateShortAndLong(string $short, string $long): self
{
if (!$this->validShort($short)) {
throw new MiniGetoptException("Short option '$short' should be one character long");
}
if (!$this->validLong($long)) {
throw new MiniGetoptException("Long option '$long' should be at least two characters long");
}
if ($this->emptyString($short) && $this->emptyString($long)) {
throw new MiniGetoptException("You should define at least short option or long option");
}
return $this;
} | @param string $short
@param string $long
@return \Jawira\MiniGetopt\MiniGetopt
@throws \Jawira\MiniGetopt\MiniGetoptException | https://github.com/jawira/mini-getopt/blob/f9f35409a7cd72f37a0ec9dd6a34c091e4a22c41/src/MiniGetopt.php#L198-L210 |
smalldb/libSmalldb | class/FlupdoGenericListing.php | FlupdoGenericListing.query | public function query()
{
if ($this->result === null) {
$this->before_called = true;
foreach ($this->before_query as $callable) {
$callable();
}
try {
$this->result = $this->query->query();
$this->result->setFetchMode(\PDO::FETCH_ASSOC);
}
catch (\Smalldb\Flupdo\FlupdoSqlException $ex) {
error_log("Failed SQL query:\n".$this->query->getSqlQuery());
error_log("Parameters of failed SQL query:\n".$this->query->getSqlParams());
throw $ex;
}
} else {
throw new RuntimeException('Query already performed.');
}
return $this->result;
} | php | public function query()
{
if ($this->result === null) {
$this->before_called = true;
foreach ($this->before_query as $callable) {
$callable();
}
try {
$this->result = $this->query->query();
$this->result->setFetchMode(\PDO::FETCH_ASSOC);
}
catch (\Smalldb\Flupdo\FlupdoSqlException $ex) {
error_log("Failed SQL query:\n".$this->query->getSqlQuery());
error_log("Parameters of failed SQL query:\n".$this->query->getSqlParams());
throw $ex;
}
} else {
throw new RuntimeException('Query already performed.');
}
return $this->result;
} | Execute SQL query or do whatever is required to get this listing
populated. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoGenericListing.php#L456-L477 |
smalldb/libSmalldb | class/FlupdoGenericListing.php | FlupdoGenericListing.fetchAll | public function fetchAll()
{
if ($this->result === null) {
$this->query();
}
$machine = $this->machine;
$id_keys = $this->machine->describeId();
if (count($id_keys) == 1) {
$list = array();
while(($properties = $this->result->fetch(\PDO::FETCH_ASSOC))) {
$item = $machine->hotRef($machine->decodeProperties($properties));
$list[$item->id] = $item;
}
return $list;
} else {
return array_map(function($properties) use ($machine) {
return $machine->hotRef($machine->decodeProperties($properties));
}, $this->result->fetchAll(\PDO::FETCH_ASSOC));
}
} | php | public function fetchAll()
{
if ($this->result === null) {
$this->query();
}
$machine = $this->machine;
$id_keys = $this->machine->describeId();
if (count($id_keys) == 1) {
$list = array();
while(($properties = $this->result->fetch(\PDO::FETCH_ASSOC))) {
$item = $machine->hotRef($machine->decodeProperties($properties));
$list[$item->id] = $item;
}
return $list;
} else {
return array_map(function($properties) use ($machine) {
return $machine->hotRef($machine->decodeProperties($properties));
}, $this->result->fetchAll(\PDO::FETCH_ASSOC));
}
} | Returns an array of all items in the listing.
This decodes properties. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoGenericListing.php#L504-L525 |
smalldb/libSmalldb | class/FlupdoGenericListing.php | FlupdoGenericListing.getProcessedFilters | public function getProcessedFilters()
{
if ($this->result !== null) {
$q = clone $this->query; // make sure we do not modify original query
$q->uncompile();
$count = $q->select(null)->orderBy(null)->limit(null)->offset(null)
->select('COUNT(1)')
->query()
->fetchColumn();
$filters = $this->query_filters;
$filters['_count'] = $count;
$this->calculateAdditionalFiltersData($filters);
return $filters;
} else {
return $this->query_filters;
}
} | php | public function getProcessedFilters()
{
if ($this->result !== null) {
$q = clone $this->query; // make sure we do not modify original query
$q->uncompile();
$count = $q->select(null)->orderBy(null)->limit(null)->offset(null)
->select('COUNT(1)')
->query()
->fetchColumn();
$filters = $this->query_filters;
$filters['_count'] = $count;
$this->calculateAdditionalFiltersData($filters);
return $filters;
} else {
return $this->query_filters;
}
} | Get filter configuration (processed and filled with pagination
data). This method should be called after query(), otherwise it will
not contain `total_count`.
The `total_count` is calculated using second query, same as the
primary query, but with `COUNT(*)` in `SELECT` clause, and
limit & offset removed (everything else is preserved). This is a few
orders of magnitude faster than SQL_CALC_FOUND_ROWS. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoGenericListing.php#L538-L554 |
smalldb/libSmalldb | class/FlupdoGenericListing.php | FlupdoGenericListing.calculateAdditionalFiltersData | protected function calculateAdditionalFiltersData(& $filters)
{
if (!empty($this->additional_filters_data)) {
foreach ($this->additional_filters_data as $f => $src) {
if (isset($src['query'])) {
$filters[$f] = $this->query->pdo->query($src['query'])->fetchColumn();
}
}
}
} | php | protected function calculateAdditionalFiltersData(& $filters)
{
if (!empty($this->additional_filters_data)) {
foreach ($this->additional_filters_data as $f => $src) {
if (isset($src['query'])) {
$filters[$f] = $this->query->pdo->query($src['query'])->fetchColumn();
}
}
}
} | Calculate additional filter data.
@param $filters Filters to populate with additional data.
@return Nothing. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoGenericListing.php#L581-L590 |
smalldb/libSmalldb | class/FlupdoGenericListing.php | FlupdoGenericListing.setupSphinxSearch | protected function setupSphinxSearch($filter_name, $value, $machine_filter)
{
$sphinx_key_column = $this->query->quoteIdent($machine_filter['sphinx_key_column']);
$temp_table = $this->query->quoteIdent('_sphinx_temp_'.$filter_name);
$index_name = $this->query->quoteIdent($machine_filter['index_name']);
$this->query->where("$sphinx_key_column IN (SELECT $temp_table.id FROM $temp_table)");
$this->before_query[] = function() use ($temp_table, $index_name, $value, $machine_filter) {
$this->query->pdo->query("CREATE TEMPORARY TABLE $temp_table (`id` INT(11) NOT NULL)");
$sq = $this->sphinx->select('*')->from($index_name)->where('MATCH(?)', $value);
if (!empty($machine_filter['sphinx_option'])) {
$sq->option($machine_filter['sphinx_option']);
}
// TODO: Add param. conditions here
$sr = $sq->query();
$ins = $this->query->pdo->prepare("INSERT INTO $temp_table (id) VALUES (:id)");
foreach ($sr as $row) {
$ins->execute(array('id' => $row['id']));
}
};
$this->after_query[] = function() use ($temp_table) {
$this->query->pdo->query("DROP TEMPORARY TABLE $temp_table");
};
} | php | protected function setupSphinxSearch($filter_name, $value, $machine_filter)
{
$sphinx_key_column = $this->query->quoteIdent($machine_filter['sphinx_key_column']);
$temp_table = $this->query->quoteIdent('_sphinx_temp_'.$filter_name);
$index_name = $this->query->quoteIdent($machine_filter['index_name']);
$this->query->where("$sphinx_key_column IN (SELECT $temp_table.id FROM $temp_table)");
$this->before_query[] = function() use ($temp_table, $index_name, $value, $machine_filter) {
$this->query->pdo->query("CREATE TEMPORARY TABLE $temp_table (`id` INT(11) NOT NULL)");
$sq = $this->sphinx->select('*')->from($index_name)->where('MATCH(?)', $value);
if (!empty($machine_filter['sphinx_option'])) {
$sq->option($machine_filter['sphinx_option']);
}
// TODO: Add param. conditions here
$sr = $sq->query();
$ins = $this->query->pdo->prepare("INSERT INTO $temp_table (id) VALUES (:id)");
foreach ($sr as $row) {
$ins->execute(array('id' => $row['id']));
}
};
$this->after_query[] = function() use ($temp_table) {
$this->query->pdo->query("DROP TEMPORARY TABLE $temp_table");
};
} | Setup query for lookup in Sphinx search engine.
Since Sphinx is accessed using standalone MySQL connection, this
will create temporary table and populate it with the fulltext search
result. Then the temporary table will be used to access and filter
the original query. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoGenericListing.php#L601-L627 |
alxmsl/Cli | source/Option.php | Option.setValue | public function setValue($value) {
switch ($this->type) {
case self::TYPE_BOOLEAN:
$this->value = (bool) $value;
break;
case self::TYPE_STRING:
$this->value = (string) $value;
break;
}
return $this;
} | php | public function setValue($value) {
switch ($this->type) {
case self::TYPE_BOOLEAN:
$this->value = (bool) $value;
break;
case self::TYPE_STRING:
$this->value = (string) $value;
break;
}
return $this;
} | Option value setter
@param string|bool $value option value
@return Option self | https://github.com/alxmsl/Cli/blob/806fc2baa23e5a3d32734a4b913c3730342a8bb1/source/Option.php#L123-L133 |
bariew/yii2-node-tree | ARTreeBehavior.php | ARTreeBehavior.menuWidget | public function menuWidget($view='node', $attributes=array(), $return=false)
{
$items = $this->childrenTree($attributes);
$behavior = $this;
$widget = new ARTreeMenuWidget(compact('view', 'items', 'behavior'), $return);
return $widget->run();
} | php | public function menuWidget($view='node', $attributes=array(), $return=false)
{
$items = $this->childrenTree($attributes);
$behavior = $this;
$widget = new ARTreeMenuWidget(compact('view', 'items', 'behavior'), $return);
return $widget->run();
} | /* MENU WIDGET | https://github.com/bariew/yii2-node-tree/blob/c2ecfceb0d3a34efd33b32bcb4a6e95642492d75/ARTreeBehavior.php#L53-L59 |
bariew/yii2-node-tree | ARTreeBehavior.php | ARTreeBehavior.childrenTree | public function childrenTree($conditions = array())
{
$items = $this->owner->find()->where(
array_merge($this->getDescendantCondition(), $conditions)
)->all();
return $this->toTree($items);
} | php | public function childrenTree($conditions = array())
{
$items = $this->owner->find()->where(
array_merge($this->getDescendantCondition(), $conditions)
)->all();
return $this->toTree($items);
} | /* TREE BUILD | https://github.com/bariew/yii2-node-tree/blob/c2ecfceb0d3a34efd33b32bcb4a6e95642492d75/ARTreeBehavior.php#L85-L91 |
bariew/yii2-node-tree | ARTreeBehavior.php | ARTreeBehavior.createUrl | protected function createUrl()
{
$oldUrl = $this->get('url');
$newUrl = (($parent = $this->getParent()) ? $parent->{$this->url} : '/') . $this->get('slug') . "/";
if($newUrl == $oldUrl){
return false;
}
if (!$this->get('parent_id')) {
return $this->set('slug', '');
}
return ($oldUrl)
? \Yii::$app->db->createCommand("
UPDATE {$this->owner->tableName()}
SET {$this->url} = REPLACE({$this->url}, '{$oldUrl}', '{$newUrl}')
WHERE {$this->url} LIKE '{$oldUrl}%'
")->execute()
: $this->set('url', $newUrl);
} | php | protected function createUrl()
{
$oldUrl = $this->get('url');
$newUrl = (($parent = $this->getParent()) ? $parent->{$this->url} : '/') . $this->get('slug') . "/";
if($newUrl == $oldUrl){
return false;
}
if (!$this->get('parent_id')) {
return $this->set('slug', '');
}
return ($oldUrl)
? \Yii::$app->db->createCommand("
UPDATE {$this->owner->tableName()}
SET {$this->url} = REPLACE({$this->url}, '{$oldUrl}', '{$newUrl}')
WHERE {$this->url} LIKE '{$oldUrl}%'
")->execute()
: $this->set('url', $newUrl);
} | /* TREE UPDATE | https://github.com/bariew/yii2-node-tree/blob/c2ecfceb0d3a34efd33b32bcb4a6e95642492d75/ARTreeBehavior.php#L132-L149 |
internetofvoice/libvoice | src/Alexa/Response/Card/Standard.php | Standard.setSmallImageUrl | public function setSmallImageUrl($smallImageUrl) {
if (strlen($smallImageUrl) > self::MAX_URL_CHARS) {
throw new InvalidArgumentException('Small image URL exceeds ' . self::MAX_URL_CHARS . ' characters.');
}
$this->smallImageUrl = $smallImageUrl;
return $this;
} | php | public function setSmallImageUrl($smallImageUrl) {
if (strlen($smallImageUrl) > self::MAX_URL_CHARS) {
throw new InvalidArgumentException('Small image URL exceeds ' . self::MAX_URL_CHARS . ' characters.');
}
$this->smallImageUrl = $smallImageUrl;
return $this;
} | PNG or JPG, recommended size: 720 x 480
@param string $smallImageUrl
@return Standard
@throws InvalidArgumentException | https://github.com/internetofvoice/libvoice/blob/15dc4420ddd52234c53902752dc0da16b9d4acdf/src/Alexa/Response/Card/Standard.php#L95-L103 |
internetofvoice/libvoice | src/Alexa/Response/Card/Standard.php | Standard.setLargeImageUrl | public function setLargeImageUrl($largeImageUrl) {
if (strlen($largeImageUrl) > self::MAX_URL_CHARS) {
throw new InvalidArgumentException('Large image URL exceeds ' . self::MAX_URL_CHARS . ' characters.');
}
$this->largeImageUrl = $largeImageUrl;
return $this;
} | php | public function setLargeImageUrl($largeImageUrl) {
if (strlen($largeImageUrl) > self::MAX_URL_CHARS) {
throw new InvalidArgumentException('Large image URL exceeds ' . self::MAX_URL_CHARS . ' characters.');
}
$this->largeImageUrl = $largeImageUrl;
return $this;
} | PNG or JPG, recommended size: 1200 x 800
@param string $largeImageUrl
@return Standard
@throws InvalidArgumentException | https://github.com/internetofvoice/libvoice/blob/15dc4420ddd52234c53902752dc0da16b9d4acdf/src/Alexa/Response/Card/Standard.php#L121-L129 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.firstPage | public function firstPage()
{
// return '<a href="'.$this->getUrl().'" class="number" title="1">'.$this->text['first'].'</a>';
$first = Html::a($this->text['first'], $this->getUrl(1));
$this->html['first'] = $this->hasListElement($first);
return $this;
} | php | public function firstPage()
{
// return '<a href="'.$this->getUrl().'" class="number" title="1">'.$this->text['first'].'</a>';
$first = Html::a($this->text['first'], $this->getUrl(1));
$this->html['first'] = $this->hasListElement($first);
return $this;
} | 得到回到第一页字符串
@return $this | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L54-L62 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.prevPage | public function prevPage()
{
$page = (int)$this->getOption('page', 1);
if ($page > 1) {
$prev = Html::a($this->text['prev'], $this->getUrl($this->prevPage));
$prev = $this->hasListElement($prev);
}
$this->html['prev'] = isset($prev) ? $prev : '';
return $this;
} | php | public function prevPage()
{
$page = (int)$this->getOption('page', 1);
if ($page > 1) {
$prev = Html::a($this->text['prev'], $this->getUrl($this->prevPage));
$prev = $this->hasListElement($prev);
}
$this->html['prev'] = isset($prev) ? $prev : '';
return $this;
} | 得到上一页,当前页数大于1时,出现 ‘上一页’ 按钮
@return $this | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L68-L81 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.prevAcrossPages | public function prevAcrossPages()
{
$prevAcrossPages = $this->options['page'] - $this->options['btnNum'];
if ($prevAcrossPages > 0) {
$text = sprintf($this->text['prevs'], $this->options['btnNum']);
// return '<a href="'.$this->getUrl($prevAcrossPages).'" class="number" title="'.$text.'">'.$text.'</a>';
$prevs = Html::a($text, $this->getUrl($prevAcrossPages), ['title' => $text]);
$prevs = $this->hasListElement($prevs);
}
$this->html['prevs'] = isset($prevs) ? $prevs : '';
return $this;
} | php | public function prevAcrossPages()
{
$prevAcrossPages = $this->options['page'] - $this->options['btnNum'];
if ($prevAcrossPages > 0) {
$text = sprintf($this->text['prevs'], $this->options['btnNum']);
// return '<a href="'.$this->getUrl($prevAcrossPages).'" class="number" title="'.$text.'">'.$text.'</a>';
$prevs = Html::a($text, $this->getUrl($prevAcrossPages), ['title' => $text]);
$prevs = $this->hasListElement($prevs);
}
$this->html['prevs'] = isset($prevs) ? $prevs : '';
return $this;
} | 向上跳转 $this->btnNum 的页数
@return $this | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L87-L101 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.numberPageBtn | public function numberPageBtn()
{
$numBtnPage = '';
$page = (int)$this->getOption('page', 1);
for ($i = $this->firstNumBtn; $i <= $this->lastNumBtn; $i++) {
if ($i === $page) {
//给当前页按钮设置额外样式
// $numBtnPage .='<a href="'.$this->getUrl($i).'" class="number current" title="'.$i.'">'.$i.'</a>';
$a = Html::a($i, '', ['title' => $i]);
$numBtnPage .= $this->hasListElement($a, ['class' => $this->elements['list']['currentClass']]);
} else {
// $numBtnPage .='<a href="'.$this->getUrl($i).'" class="number" title="'.$i.'">'.$i.'</a>';
$a = Html::a($i, $this->getUrl($i), ['title' => $i]);
$numBtnPage .= $this->hasListElement($a);
}
}
$this->html['numbers'] = $numBtnPage;
return $this;
} | php | public function numberPageBtn()
{
$numBtnPage = '';
$page = (int)$this->getOption('page', 1);
for ($i = $this->firstNumBtn; $i <= $this->lastNumBtn; $i++) {
if ($i === $page) {
//给当前页按钮设置额外样式
// $numBtnPage .='<a href="'.$this->getUrl($i).'" class="number current" title="'.$i.'">'.$i.'</a>';
$a = Html::a($i, '', ['title' => $i]);
$numBtnPage .= $this->hasListElement($a, ['class' => $this->elements['list']['currentClass']]);
} else {
// $numBtnPage .='<a href="'.$this->getUrl($i).'" class="number" title="'.$i.'">'.$i.'</a>';
$a = Html::a($i, $this->getUrl($i), ['title' => $i]);
$numBtnPage .= $this->hasListElement($a);
}
}
$this->html['numbers'] = $numBtnPage;
return $this;
} | 得到数字按钮分页字符串
@return $this | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L107-L128 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.nextAcrossPages | public function nextAcrossPages()
{
$nextAcrossPages = $this->options['page'] + $this->options['btnNum'];
if ($nextAcrossPages < $this->pageTotal) {
$text = sprintf($this->text['nexts'], $this->options['btnNum']);
$nexts = Html::a($text, $this->getUrl($nextAcrossPages), ['title' => $text]);
$nexts = $this->hasListElement($nexts);
}
$this->html['nexts'] = isset($nexts) ? $nexts : '';
return $this;
} | php | public function nextAcrossPages()
{
$nextAcrossPages = $this->options['page'] + $this->options['btnNum'];
if ($nextAcrossPages < $this->pageTotal) {
$text = sprintf($this->text['nexts'], $this->options['btnNum']);
$nexts = Html::a($text, $this->getUrl($nextAcrossPages), ['title' => $text]);
$nexts = $this->hasListElement($nexts);
}
$this->html['nexts'] = isset($nexts) ? $nexts : '';
return $this;
} | 向下跳转 $this->btnNum 的页数
@return $this | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L134-L147 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.nextPage | public function nextPage()
{
if ($this->options['page'] < $this->pageTotal) {
$next = Html::a($this->text['next'], $this->getUrl($this->nextPage));
$next = $this->hasListElement($next);
}
$this->html['next'] = isset($next) ? $next : '';
return $this;
} | php | public function nextPage()
{
if ($this->options['page'] < $this->pageTotal) {
$next = Html::a($this->text['next'], $this->getUrl($this->nextPage));
$next = $this->hasListElement($next);
}
$this->html['next'] = isset($next) ? $next : '';
return $this;
} | 得到下一页,当前页数小于总页数时,出现 ‘下一页’ 按钮
@return $this | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L153-L163 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.lastPage | public function lastPage()
{
$last = Html::a($this->text['last'], $this->getUrl($this->pageTotal), ['title' => $this->text['last']]);
$this->html['last'] = $this->hasListElement($last);
return $this;
} | php | public function lastPage()
{
$last = Html::a($this->text['last'], $this->getUrl($this->pageTotal), ['title' => $this->text['last']]);
$this->html['last'] = $this->hasListElement($last);
return $this;
} | 得到跳到尾页字符串
@return $this | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L169-L176 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.jumpPage | public function jumpPage()
{
if ($this->pageTotal <= 1) {
return '';
}
$jumpPage = ' <input type="button" class="button jump-page-btn" value="' . $this->text['jumpTo'] . '"
onclick="javascript:var jumpPN = document.getElementById(\'jumpPageNum\');
if (jumpPN.value<=' . $this->pageTotal . '){
location.href=\'' . $this->getUrl() . '\'+jumpPN.value;
}">';
$jumpPage .= ' <input type="text" class="page-num-input" id="jumpPageNum"
style="width: 35px;" value="' . $this->options['page'] . '" onkeydown = "javascript:
if (event.keyCode==13 && this.value<=' . $this->pageTotal . '){
location.href=\'' . $this->getUrl() . '\'+this.value;
}"> ';
$this->html['jump'] = $jumpPage;
return $this;
} | php | public function jumpPage()
{
if ($this->pageTotal <= 1) {
return '';
}
$jumpPage = ' <input type="button" class="button jump-page-btn" value="' . $this->text['jumpTo'] . '"
onclick="javascript:var jumpPN = document.getElementById(\'jumpPageNum\');
if (jumpPN.value<=' . $this->pageTotal . '){
location.href=\'' . $this->getUrl() . '\'+jumpPN.value;
}">';
$jumpPage .= ' <input type="text" class="page-num-input" id="jumpPageNum"
style="width: 35px;" value="' . $this->options['page'] . '" onkeydown = "javascript:
if (event.keyCode==13 && this.value<=' . $this->pageTotal . '){
location.href=\'' . $this->getUrl() . '\'+this.value;
}"> ';
$this->html['jump'] = $jumpPage;
return $this;
} | 输入页数跳转
@return $this|string | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L197-L217 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.selectPage | public function selectPage()
{
if ($this->pageTotal <= 1) {
return '';
}
$page = (int)$this->getOption('page', 1);
$select = ' <select class="page-num-input" style="max-height: 400px"
onchange="javascript:location.href=\'' . $this->getUrl() . '\'+this.value;">';
for ($i = 1; $i <= $this->pageTotal; $i++) {
$select .= ($page === $i) ?
'<option value="' . $i . '" selected="selected"">' . $i . '</option>' :
'<option value="' . $i . '" >' . $i . '</option>';
}
$select .= '</select> ';
$this->html['select'] = $select;
return $this;
} | php | public function selectPage()
{
if ($this->pageTotal <= 1) {
return '';
}
$page = (int)$this->getOption('page', 1);
$select = ' <select class="page-num-input" style="max-height: 400px"
onchange="javascript:location.href=\'' . $this->getUrl() . '\'+this.value;">';
for ($i = 1; $i <= $this->pageTotal; $i++) {
$select .= ($page === $i) ?
'<option value="' . $i . '" selected="selected"">' . $i . '</option>' :
'<option value="' . $i . '" >' . $i . '</option>';
}
$select .= '</select> ';
$this->html['select'] = $select;
return $this;
} | select 下拉选择框跳转
@return $this|string | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L223-L244 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.useStyle | public function useStyle($type = 'full')
{
switch (trim($type)) {
case 'mini'://最简单
$this->prevPage()->nextPage();
break;
case 'simple'://simple
$this->firstPage()->numberPageBtn()->lastPage()->totalStr();
break;
case 'normal'://常用
$this->prevAcrossPages()->prevPage()
->numberPageBtn()->nextPage()->nextAcrossPages()->totalStr();
break;
case 'normal_select'://常用+select
$this->prevAcrossPages()->prevPage()->numberPageBtn()->nextPage()
->nextAcrossPages()->selectPage()->totalStr();
break;
case 'normal_jump'://常用+input jump
$this->prevAcrossPages()->prevPage()->numberPageBtn()->nextPage()
->nextAcrossPages()->jumpPage()->totalStr();
break;
default://完整的组装
$this->firstPage()->prevAcrossPages()->prevPage()
->numberPageBtn()->nextPage()->nextAcrossPages()
->lastPage()->totalStr()->selectPage()->jumpPage();
break;
}
return $this;
} | php | public function useStyle($type = 'full')
{
switch (trim($type)) {
case 'mini'://最简单
$this->prevPage()->nextPage();
break;
case 'simple'://simple
$this->firstPage()->numberPageBtn()->lastPage()->totalStr();
break;
case 'normal'://常用
$this->prevAcrossPages()->prevPage()
->numberPageBtn()->nextPage()->nextAcrossPages()->totalStr();
break;
case 'normal_select'://常用+select
$this->prevAcrossPages()->prevPage()->numberPageBtn()->nextPage()
->nextAcrossPages()->selectPage()->totalStr();
break;
case 'normal_jump'://常用+input jump
$this->prevAcrossPages()->prevPage()->numberPageBtn()->nextPage()
->nextAcrossPages()->jumpPage()->totalStr();
break;
default://完整的组装
$this->firstPage()->prevAcrossPages()->prevPage()
->numberPageBtn()->nextPage()->nextAcrossPages()
->lastPage()->totalStr()->selectPage()->jumpPage();
break;
}
return $this;
} | 得到组装后的分页字符串 | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L249-L279 |
inhere/php-library-plus | libs/Html/ExtendedPagination.php | ExtendedPagination.hasListElement | private function hasListElement($ele, array $attrs = [])
{
if ($this->elements['list']['tag'] !== '') {
$listEle = $this->elements['list']['tag'];
return Html::tag($listEle, $ele, $attrs);
}
return $ele;
} | php | private function hasListElement($ele, array $attrs = [])
{
if ($this->elements['list']['tag'] !== '') {
$listEle = $this->elements['list']['tag'];
return Html::tag($listEle, $ele, $attrs);
}
return $ele;
} | 添加 a 的外部元素 li | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Html/ExtendedPagination.php#L282-L291 |
wearesho-team/cpa-integration | src/SalesDoubler/PostbackService.php | PostbackService.send | public function send(ConversionInterface $conversion): ResponseInterface
{
if (!$conversion instanceof Conversion) {
throw new UnsupportedConversionTypeException($this, $conversion);
}
$previousSentConversion = $this->repository->pull(
$conversion->getId(),
get_class($conversion)
);
if ($previousSentConversion instanceof StoredConversionInterface) {
throw new DuplicatedConversionException($conversion);
}
$request = new Request("get", $this->getPath($conversion));
$response = $this->client->send($request);
$this->repository->push($conversion, $response);
return $response;
} | php | public function send(ConversionInterface $conversion): ResponseInterface
{
if (!$conversion instanceof Conversion) {
throw new UnsupportedConversionTypeException($this, $conversion);
}
$previousSentConversion = $this->repository->pull(
$conversion->getId(),
get_class($conversion)
);
if ($previousSentConversion instanceof StoredConversionInterface) {
throw new DuplicatedConversionException($conversion);
}
$request = new Request("get", $this->getPath($conversion));
$response = $this->client->send($request);
$this->repository->push($conversion, $response);
return $response;
} | Sending POST query to CPA network after creating conversion
@param ConversionInterface $conversion
@throws UnsupportedConversionTypeException
@throws DuplicatedConversionException
@throws RequestException
@return ResponseInterface | https://github.com/wearesho-team/cpa-integration/blob/6b78d2315e893ecf09132ae3e9d8e8c1b5ae6291/src/SalesDoubler/PostbackService.php#L88-L107 |
imatic/controller-bundle | Controller/Feature/Security/SecurityFeature.php | SecurityFeature.checkAuthorization | public function checkAuthorization($attributes, $object = null, $message = 'Access Denied.')
{
if (!$this->isGranted($attributes, $object)) {
$exception = new AccessDeniedException($message);
$exception->setAttributes($attributes);
$exception->setSubject($object);
throw $exception;
}
} | php | public function checkAuthorization($attributes, $object = null, $message = 'Access Denied.')
{
if (!$this->isGranted($attributes, $object)) {
$exception = new AccessDeniedException($message);
$exception->setAttributes($attributes);
$exception->setSubject($object);
throw $exception;
}
} | @param mixed $attributes
@param mixed $object
@param string $message
@throws AccessDeniedException | https://github.com/imatic/controller-bundle/blob/df71c12166928f9d4f1548d4ee1e09a183a68eb6/Controller/Feature/Security/SecurityFeature.php#L93-L102 |
as3io/modlr | src/StorageLayerManager.php | StorageLayerManager.getPersister | public function getPersister($key)
{
if (empty($key) || false === $this->hasPersister($key)) {
throw PersisterException::persisterNotFound($key);
}
return $this->persisters[$key];
} | php | public function getPersister($key)
{
if (empty($key) || false === $this->hasPersister($key)) {
throw PersisterException::persisterNotFound($key);
}
return $this->persisters[$key];
} | Gets a Persister service by key.
@param string $key
@return PersisterInterface
@throws PersisterException If the service was not found. | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/StorageLayerManager.php#L62-L68 |
as3io/modlr | src/StorageLayerManager.php | StorageLayerManager.getSearchClient | public function getSearchClient($key)
{
if (empty($key) || false === $this->hasSearchClient($key)) {
throw ClientException::clientNotFound($key);
}
return $this->searchClients[$key];
} | php | public function getSearchClient($key)
{
if (empty($key) || false === $this->hasSearchClient($key)) {
throw ClientException::clientNotFound($key);
}
return $this->searchClients[$key];
} | Gets a Search Client service by key.
@param string $key
@return ClientInterface
@throws ClientException If the service was not found. | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/StorageLayerManager.php#L88-L94 |
webeith/dnsbl | src/Dnsbl/Dnsbl.php | Dnsbl.check | public function check($hostname)
{
$result = array();
foreach ($this->getBlServers() as $blServer) {
$result[] = $blServer->getResolver()->execute($hostname);
}
return $result;
} | php | public function check($hostname)
{
$result = array();
foreach ($this->getBlServers() as $blServer) {
$result[] = $blServer->getResolver()->execute($hostname);
}
return $result;
} | Check hostname in all bl servers
@param string $hostname
@return Dnsbl\Resolver\Response\InterfaceResponse | https://github.com/webeith/dnsbl/blob/062e30f1ccaf6578bebe1bbe51a6a833337ba825/src/Dnsbl/Dnsbl.php#L35-L43 |
webeith/dnsbl | src/Dnsbl/Dnsbl.php | Dnsbl.checkIP | public function checkIP($ip)
{
$result = array();
foreach ($this->getBlServers() as $blServer) {
if ($blServer->supportIPv4()) {
$result[] = $blServer->getResolver()->execute($ip);
}
}
return $result;
} | php | public function checkIP($ip)
{
$result = array();
foreach ($this->getBlServers() as $blServer) {
if ($blServer->supportIPv4()) {
$result[] = $blServer->getResolver()->execute($ip);
}
}
return $result;
} | Check IP in black list
@param string $ip
@return Dnsbl\Resolver\Response\InterfaceResponse | https://github.com/webeith/dnsbl/blob/062e30f1ccaf6578bebe1bbe51a6a833337ba825/src/Dnsbl/Dnsbl.php#L52-L62 |
webeith/dnsbl | src/Dnsbl/Dnsbl.php | Dnsbl.checkDomain | public function checkDomain($hostname)
{
$result = array();
foreach ($this->getBlServers() as $blServer) {
if ($blServer->supportDomain()) {
$result[] = $blServer->getResolver()->execute($hostname);
}
}
return $result;
} | php | public function checkDomain($hostname)
{
$result = array();
foreach ($this->getBlServers() as $blServer) {
if ($blServer->supportDomain()) {
$result[] = $blServer->getResolver()->execute($hostname);
}
}
return $result;
} | Check domain name in black list
@param string $domain
@return Dnsbl\Resolver\Response\InterfaceResponse | https://github.com/webeith/dnsbl/blob/062e30f1ccaf6578bebe1bbe51a6a833337ba825/src/Dnsbl/Dnsbl.php#L70-L80 |
webeith/dnsbl | src/Dnsbl/Dnsbl.php | Dnsbl.addBlServer | public function addBlServer(Server $server)
{
if (is_null($server->getResolver())) {
throw new Resolver\NotFoundResolverException('Set the server resolver.');
}
$this->blServers[] = $server;
return $this;
} | php | public function addBlServer(Server $server)
{
if (is_null($server->getResolver())) {
throw new Resolver\NotFoundResolverException('Set the server resolver.');
}
$this->blServers[] = $server;
return $this;
} | Add the server to BlServers
@param Server $server
@exception Resolver\NotFoundResolverException
@return Dnsbl | https://github.com/webeith/dnsbl/blob/062e30f1ccaf6578bebe1bbe51a6a833337ba825/src/Dnsbl/Dnsbl.php#L91-L100 |
webeith/dnsbl | src/Dnsbl/Dnsbl.php | Dnsbl.setBlServers | public function setBlServers(array $servers)
{
$this->blServers = array();
foreach ($servers as $server) {
if ($server instanceof Server) {
if (is_null($server->getResolver())) {
throw new Resolver\NotFoundResolverException('Set the server resolver.');
}
$this->blServers[] = $server;
}
}
return $this;
} | php | public function setBlServers(array $servers)
{
$this->blServers = array();
foreach ($servers as $server) {
if ($server instanceof Server) {
if (is_null($server->getResolver())) {
throw new Resolver\NotFoundResolverException('Set the server resolver.');
}
$this->blServers[] = $server;
}
}
return $this;
} | Add the server to BlServers
@param Server $server
@exception Resolver\NotFoundResolverException
@return Dnsbl | https://github.com/webeith/dnsbl/blob/062e30f1ccaf6578bebe1bbe51a6a833337ba825/src/Dnsbl/Dnsbl.php#L111-L125 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/LinkTag.php | LinkTag.add | public function add($tag_attributes)
{
if (!empty($tag_attributes)) {
$this->__template->registry->addEntry($tag_attributes, 'link_tags');
}
return $this;
} | php | public function add($tag_attributes)
{
if (!empty($tag_attributes)) {
$this->__template->registry->addEntry($tag_attributes, 'link_tags');
}
return $this;
} | Add a link header attribute
@param array $tag_attributes The link tag attributes
@return self | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/LinkTag.php#L66-L72 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/LinkTag.php | LinkTag.set | public function set(array $tags)
{
if (!empty($tags)) {
foreach ($tags as $_tag) {
$this->add($_tag);
}
}
return $this;
} | php | public function set(array $tags)
{
if (!empty($tags)) {
foreach ($tags as $_tag) {
$this->add($_tag);
}
}
return $this;
} | Set a full links header stack
@param array $tags An array of tags definitions
@return self
@see self::add() | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/LinkTag.php#L81-L89 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/LinkTag.php | LinkTag.write | public function write($mask = '%s')
{
$str='';
// allow multi same links
// foreach($this->cleanStack( $this->get(), 'rel' ) as $entry) {
foreach ($this->get() as $entry) {
$str .= sprintf($mask, Html::writeHtmlTag('link', null, $entry, true));
}
return $str;
} | php | public function write($mask = '%s')
{
$str='';
// allow multi same links
// foreach($this->cleanStack( $this->get(), 'rel' ) as $entry) {
foreach ($this->get() as $entry) {
$str .= sprintf($mask, Html::writeHtmlTag('link', null, $entry, true));
}
return $str;
} | Write the Template Object strings ready for template display
@param string $mask A mask to write each line via "sprintf()"
@return string The string to display fot this template object | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/LinkTag.php#L107-L116 |
PhoxPHP/Glider | src/Connectors/Mysqli/MysqliConnector.php | MysqliConnector.connect | public function connect(String $host=null, String $username=null, String $password=null, String $database=null, String $collation=null, String $charset=null, String $driver=null, Array $options=[], int $port=0000)
{
$connection = new StdClass;
$host = $host == null ? $this->platformProvider->getConfig('host') : $host;
$username = $username == null ? $this->platformProvider->getConfig('username') : $username;
$password = $password == null ? $this->platformProvider->getConfig('password') : $password;
$database = $database == null ? $this->platformProvider->getConfig('database') : $database;
$collation = $collation == null ? $this->platformProvider->getConfig('collation') : $collation;
$charset = $charset == null ? $this->platformProvider->getConfig('charset') : $charset;
$connection = new mysqli($host, $username, $password, $database);
// If there is an error establishing a connection, attach the `ConnectionAttemptSubscriber` to
// the event manager to dispatch.
if ($connection->connect_error) {
// If an error occurred while establishin a connection, we'll dispatch the connect.failed
// event that will send the necessary error message.
$this->platformProvider->eventManager->dispatchEvent('connect.failed', $connection->connect_error);
}
// If `collation` is set in the configuration or we are able to get it from
// the platform provider, we will make an attempt to set the collation to the
// configuration value.
if ($this->platformProvider->getConfig('collation')) {
$this->setCollation($connection, $collation);
}
// If `charset` is set in the configuration just like the `collation`,
// we will make an attempt to set it as well.
if ($this->platformProvider->getConfig('charset')) {
$this->setCharset($connection, $charset);
}
$this->connection = $connection;
return $this->connection;
} | php | public function connect(String $host=null, String $username=null, String $password=null, String $database=null, String $collation=null, String $charset=null, String $driver=null, Array $options=[], int $port=0000)
{
$connection = new StdClass;
$host = $host == null ? $this->platformProvider->getConfig('host') : $host;
$username = $username == null ? $this->platformProvider->getConfig('username') : $username;
$password = $password == null ? $this->platformProvider->getConfig('password') : $password;
$database = $database == null ? $this->platformProvider->getConfig('database') : $database;
$collation = $collation == null ? $this->platformProvider->getConfig('collation') : $collation;
$charset = $charset == null ? $this->platformProvider->getConfig('charset') : $charset;
$connection = new mysqli($host, $username, $password, $database);
// If there is an error establishing a connection, attach the `ConnectionAttemptSubscriber` to
// the event manager to dispatch.
if ($connection->connect_error) {
// If an error occurred while establishin a connection, we'll dispatch the connect.failed
// event that will send the necessary error message.
$this->platformProvider->eventManager->dispatchEvent('connect.failed', $connection->connect_error);
}
// If `collation` is set in the configuration or we are able to get it from
// the platform provider, we will make an attempt to set the collation to the
// configuration value.
if ($this->platformProvider->getConfig('collation')) {
$this->setCollation($connection, $collation);
}
// If `charset` is set in the configuration just like the `collation`,
// we will make an attempt to set it as well.
if ($this->platformProvider->getConfig('charset')) {
$this->setCharset($connection, $charset);
}
$this->connection = $connection;
return $this->connection;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connectors/Mysqli/MysqliConnector.php#L65-L100 |
PhoxPHP/Glider | src/Connectors/Mysqli/MysqliConnector.php | MysqliConnector.getErrorMessage | public function getErrorMessage($connection=null)
{
if (!$connection instanceof mysqli) {
$this->platformProvider->eventManager->dispatchEvent('connect.failed.message.instance', 'mysqli');
}
return $connection->error;
} | php | public function getErrorMessage($connection=null)
{
if (!$connection instanceof mysqli) {
$this->platformProvider->eventManager->dispatchEvent('connect.failed.message.instance', 'mysqli');
}
return $connection->error;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connectors/Mysqli/MysqliConnector.php#L105-L111 |
PhoxPHP/Glider | src/Connectors/Mysqli/MysqliConnector.php | MysqliConnector.getErrorNumber | public function getErrorNumber($connection=null)
{
if (!$connection instanceof mysqli) {
$this->platformProvider->eventManager->dispatchEvent('connect.failed.number.instance', 'mysqli');
}
return $connection->errno;
} | php | public function getErrorNumber($connection=null)
{
if (!$connection instanceof mysqli) {
$this->platformProvider->eventManager->dispatchEvent('connect.failed.number.instance', 'mysqli');
}
return $connection->errno;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connectors/Mysqli/MysqliConnector.php#L116-L122 |
GordonSchmidt/GSImage | src/GSImage/Driver/AbstractDriver.php | AbstractDriver.getImageStorage | public function getImageStorage($image)
{
if (@file_exists('file://' . $image)) {
return DriverInterface::IMAGE_STORAGE_FILE;
} elseif (false === strpos($image, '://')) {
return DriverInterface::IMAGE_STORAGE_STRING;
} else {
return DriverInterface::IMAGE_STORAGE_URL;
}
} | php | public function getImageStorage($image)
{
if (@file_exists('file://' . $image)) {
return DriverInterface::IMAGE_STORAGE_FILE;
} elseif (false === strpos($image, '://')) {
return DriverInterface::IMAGE_STORAGE_STRING;
} else {
return DriverInterface::IMAGE_STORAGE_URL;
}
} | Get storage type of image
@param string $image
@return string | https://github.com/GordonSchmidt/GSImage/blob/c36c5ce2131ac535f5ca2d9ce7b3c66cf6f2b72d/src/GSImage/Driver/AbstractDriver.php#L29-L38 |
GordonSchmidt/GSImage | src/GSImage/Driver/AbstractDriver.php | AbstractDriver.getInfo | public function getInfo($image)
{
if (DriverInterface::IMAGE_STORAGE_STRING == $this->getImageStorage($image)) {
$image = 'data://application/octet-stream;base64,' . base64_encode($image);
}
return getimagesize($image);
} | php | public function getInfo($image)
{
if (DriverInterface::IMAGE_STORAGE_STRING == $this->getImageStorage($image)) {
$image = 'data://application/octet-stream;base64,' . base64_encode($image);
}
return getimagesize($image);
} | Get info of image
@param string $image
@return array | https://github.com/GordonSchmidt/GSImage/blob/c36c5ce2131ac535f5ca2d9ce7b3c66cf6f2b72d/src/GSImage/Driver/AbstractDriver.php#L58-L64 |
GordonSchmidt/GSImage | src/GSImage/Driver/AbstractDriver.php | AbstractDriver.ensure | public function ensure($image, $formats, $storages)
{
$storage = $this->getImageStorage($image);
$format = $this->getImageFormat($image);
$storages = is_string($storages) ? array($storages) : $storages;
$formats = is_int($formats) ? array($formats) : $formats;
if (in_array($format, $formats)) {
if (in_array($storage, $storages)) {
return $image;
} else {
$file = $this->getFileOptionForSaving($storages);
$image = $this->loadToString($image);
return $this->saveFromString($image, array('file' => $file));
}
} else {
$file = $this->getFileOptionForSaving($storages);
$resource = $this->load($image);
return $this->save($resource, array('file' => $file, 'format' => $formats[0]));
}
} | php | public function ensure($image, $formats, $storages)
{
$storage = $this->getImageStorage($image);
$format = $this->getImageFormat($image);
$storages = is_string($storages) ? array($storages) : $storages;
$formats = is_int($formats) ? array($formats) : $formats;
if (in_array($format, $formats)) {
if (in_array($storage, $storages)) {
return $image;
} else {
$file = $this->getFileOptionForSaving($storages);
$image = $this->loadToString($image);
return $this->saveFromString($image, array('file' => $file));
}
} else {
$file = $this->getFileOptionForSaving($storages);
$resource = $this->load($image);
return $this->save($resource, array('file' => $file, 'format' => $formats[0]));
}
} | Ensure certain image storages und formats
@param string $image
@param array|int $formats
@param array|string $storages
@return string | https://github.com/GordonSchmidt/GSImage/blob/c36c5ce2131ac535f5ca2d9ce7b3c66cf6f2b72d/src/GSImage/Driver/AbstractDriver.php#L74-L94 |
GordonSchmidt/GSImage | src/GSImage/Driver/AbstractDriver.php | AbstractDriver.getFileOptionForSaving | protected function getFileOptionForSaving($storages)
{
if (in_array(DriverInterface::IMAGE_STORAGE_STRING, $storages)) {
return null;
} elseif (in_array(DriverInterface::IMAGE_STORAGE_FILE, $storages)) {
return sys_get_temp_dir() . '/tmp-image-' . rand();
} else {
throw new Exception\RuntimeException('cannot save to url storage');
}
} | php | protected function getFileOptionForSaving($storages)
{
if (in_array(DriverInterface::IMAGE_STORAGE_STRING, $storages)) {
return null;
} elseif (in_array(DriverInterface::IMAGE_STORAGE_FILE, $storages)) {
return sys_get_temp_dir() . '/tmp-image-' . rand();
} else {
throw new Exception\RuntimeException('cannot save to url storage');
}
} | Get file option from storages for saving
@param array $storages
@return string|null | https://github.com/GordonSchmidt/GSImage/blob/c36c5ce2131ac535f5ca2d9ce7b3c66cf6f2b72d/src/GSImage/Driver/AbstractDriver.php#L102-L111 |
GordonSchmidt/GSImage | src/GSImage/Driver/AbstractDriver.php | AbstractDriver.save | public function save($image, $options)
{
$image = $this->saveToString($image, $options);
return $this->saveFromString($image, $options);
} | php | public function save($image, $options)
{
$image = $this->saveToString($image, $options);
return $this->saveFromString($image, $options);
} | Save image
@param resource $image
@param array $options
@return string | https://github.com/GordonSchmidt/GSImage/blob/c36c5ce2131ac535f5ca2d9ce7b3c66cf6f2b72d/src/GSImage/Driver/AbstractDriver.php#L132-L136 |
GordonSchmidt/GSImage | src/GSImage/Driver/AbstractDriver.php | AbstractDriver.loadToString | public function loadToString($image)
{
$srcStorage = $this->getImageStorage($image);
if ($srcStorage !== DriverInterface::IMAGE_STORAGE_STRING) {
$image = @file_get_contents($image);
if (false === $image) {
throw new Exception\RuntimeException('could not load image');
}
}
return $image;
} | php | public function loadToString($image)
{
$srcStorage = $this->getImageStorage($image);
if ($srcStorage !== DriverInterface::IMAGE_STORAGE_STRING) {
$image = @file_get_contents($image);
if (false === $image) {
throw new Exception\RuntimeException('could not load image');
}
}
return $image;
} | Load image to string
@param string $image
@return string | https://github.com/GordonSchmidt/GSImage/blob/c36c5ce2131ac535f5ca2d9ce7b3c66cf6f2b72d/src/GSImage/Driver/AbstractDriver.php#L144-L154 |
GordonSchmidt/GSImage | src/GSImage/Driver/AbstractDriver.php | AbstractDriver.saveFromString | public function saveFromString($image, $options = array())
{
if (isset($options['file'])) {
if (false === @file_put_contents($options['file'], $image)) {
throw new Exception\RuntimeException('could not save image');
}
return $options['file'];
}
return $image;
} | php | public function saveFromString($image, $options = array())
{
if (isset($options['file'])) {
if (false === @file_put_contents($options['file'], $image)) {
throw new Exception\RuntimeException('could not save image');
}
return $options['file'];
}
return $image;
} | Save image from string
@param string $image
@param array $options
@return string | https://github.com/GordonSchmidt/GSImage/blob/c36c5ce2131ac535f5ca2d9ce7b3c66cf6f2b72d/src/GSImage/Driver/AbstractDriver.php#L163-L172 |
Tuna-CMS/tuna-bundle | DependencyInjection/TunaCMSAdminExtension.php | TunaCMSAdminExtension.prepend | public function prepend(ContainerBuilder $container)
{
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$configs = $container->getExtensionConfig($this->getAlias());
$this->resolveArrayParameters($container, $configs);
$config = $this->processConfiguration(new Configuration(), $configs);
$this->setParameters($container, $config);
} | php | public function prepend(ContainerBuilder $container)
{
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$configs = $container->getExtensionConfig($this->getAlias());
$this->resolveArrayParameters($container, $configs);
$config = $this->processConfiguration(new Configuration(), $configs);
$this->setParameters($container, $config);
} | {@inheritDoc} | https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/DependencyInjection/TunaCMSAdminExtension.php#L43-L52 |
adrenalinkin/enum-mapper | Mapper/AbstractEnumMapper.php | AbstractEnumMapper.getAllowedDbValues | public function getAllowedDbValues(array $except = [])
{
$map = $this->getMap();
$dbValues = array_diff(array_keys($map), $except);
return $dbValues;
} | php | public function getAllowedDbValues(array $except = [])
{
$map = $this->getMap();
$dbValues = array_diff(array_keys($map), $except);
return $dbValues;
} | Returns list of the all registered database values
@param array $except List of the database values which should be excluded
@return array | https://github.com/adrenalinkin/enum-mapper/blob/3385e6cdf75f7f9863cd3222ece76de1a3e5961d/Mapper/AbstractEnumMapper.php#L81-L87 |
adrenalinkin/enum-mapper | Mapper/AbstractEnumMapper.php | AbstractEnumMapper.getAllowedHumanValues | public function getAllowedHumanValues(array $except = [])
{
$map = $this->getMap();
$humanValues = array_diff(array_values($map), $except);
return $humanValues;
} | php | public function getAllowedHumanValues(array $except = [])
{
$map = $this->getMap();
$humanValues = array_diff(array_values($map), $except);
return $humanValues;
} | Returns list of the all registered humanized values
@param array $except List of the humanized values which should be excluded
@return array | https://github.com/adrenalinkin/enum-mapper/blob/3385e6cdf75f7f9863cd3222ece76de1a3e5961d/Mapper/AbstractEnumMapper.php#L96-L102 |
adrenalinkin/enum-mapper | Mapper/AbstractEnumMapper.php | AbstractEnumMapper.getMap | public function getMap()
{
$result = [];
foreach ($this->getConstants() as $dbName => $dbValue) {
if (0 === strpos($dbName, self::PREFIX_DB)) {
$result[$dbValue] = $this->getAppropriateConstValue(self::PREFIX_DB, $dbName);
}
}
return $result;
} | php | public function getMap()
{
$result = [];
foreach ($this->getConstants() as $dbName => $dbValue) {
if (0 === strpos($dbName, self::PREFIX_DB)) {
$result[$dbValue] = $this->getAppropriateConstValue(self::PREFIX_DB, $dbName);
}
}
return $result;
} | Returns map of the all registered values in the 'key' => 'value' pairs.
The 'key' equal to database value and the 'value' equal to humanized value.
@return array | https://github.com/adrenalinkin/enum-mapper/blob/3385e6cdf75f7f9863cd3222ece76de1a3e5961d/Mapper/AbstractEnumMapper.php#L110-L121 |
adrenalinkin/enum-mapper | Mapper/AbstractEnumMapper.php | AbstractEnumMapper.getRandomDbValue | public function getRandomDbValue(array $except = [])
{
$values = $this->getAllowedDbValues($except);
shuffle($values);
return array_shift($values);
} | php | public function getRandomDbValue(array $except = [])
{
$values = $this->getAllowedDbValues($except);
shuffle($values);
return array_shift($values);
} | Returns random database value
@param array $except List of the database values which should be excluded
@return string|int | https://github.com/adrenalinkin/enum-mapper/blob/3385e6cdf75f7f9863cd3222ece76de1a3e5961d/Mapper/AbstractEnumMapper.php#L130-L137 |
adrenalinkin/enum-mapper | Mapper/AbstractEnumMapper.php | AbstractEnumMapper.getRandomHumanValue | public function getRandomHumanValue(array $except = [])
{
$values = $this->getAllowedHumanValues($except);
shuffle($values);
return array_shift($values);
} | php | public function getRandomHumanValue(array $except = [])
{
$values = $this->getAllowedHumanValues($except);
shuffle($values);
return array_shift($values);
} | Returns random humanized value
@param array $except List of the humanized values which should be excluded
@return string|int | https://github.com/adrenalinkin/enum-mapper/blob/3385e6cdf75f7f9863cd3222ece76de1a3e5961d/Mapper/AbstractEnumMapper.php#L146-L153 |
adrenalinkin/enum-mapper | Mapper/AbstractEnumMapper.php | AbstractEnumMapper.getAppropriateConstValue | protected function getAppropriateConstValue($prefixFrom, $constName)
{
$prefixTo = $prefixFrom === self::PREFIX_DB ? self::PREFIX_HUMAN : self::PREFIX_DB;
$count = 1;
$constName = str_replace($prefixFrom, $prefixTo, $constName, $count);
return constant('static::'.$constName);
} | php | protected function getAppropriateConstValue($prefixFrom, $constName)
{
$prefixTo = $prefixFrom === self::PREFIX_DB ? self::PREFIX_HUMAN : self::PREFIX_DB;
$count = 1;
$constName = str_replace($prefixFrom, $prefixTo, $constName, $count);
return constant('static::'.$constName);
} | Returns appropriated pair value
@param string $prefixFrom Constant prefix which determine what the value should be returns
put self::PREFIX_DB to get appropriated humanized value
or self::PREFIX_HUMAN to get appropriated database value
@param string $constName Constant name which should be processed
@return int|string | https://github.com/adrenalinkin/enum-mapper/blob/3385e6cdf75f7f9863cd3222ece76de1a3e5961d/Mapper/AbstractEnumMapper.php#L165-L172 |
adrenalinkin/enum-mapper | Mapper/AbstractEnumMapper.php | AbstractEnumMapper.convert | private function convert($value, $prefixFrom)
{
foreach ($this->getConstants() as $constName => $constValue) {
// process constant if she's does start from reserved prefix and values was equals
if (0 === strpos($constName, $prefixFrom) && $value === $constValue) {
return $this->getAppropriateConstValue($prefixFrom, $constName);
}
}
throw new UndefinedMapValueException($this->getClassName(), $value);
} | php | private function convert($value, $prefixFrom)
{
foreach ($this->getConstants() as $constName => $constValue) {
// process constant if she's does start from reserved prefix and values was equals
if (0 === strpos($constName, $prefixFrom) && $value === $constValue) {
return $this->getAppropriateConstValue($prefixFrom, $constName);
}
}
throw new UndefinedMapValueException($this->getClassName(), $value);
} | Returns appropriated value by received origin value. Humanized value by received database value and vise versa.
@param string|int $value Value for convert
@param string $prefixFrom Constant prefix which determine what the value should be returns
put self::PREFIX_DB to get appropriated humanized value
or self::PREFIX_HUMAN to get appropriated database value
@throws UndefinedMapValueException When received value does not exists
@return string|int | https://github.com/adrenalinkin/enum-mapper/blob/3385e6cdf75f7f9863cd3222ece76de1a3e5961d/Mapper/AbstractEnumMapper.php#L186-L196 |
adrenalinkin/enum-mapper | Mapper/AbstractEnumMapper.php | AbstractEnumMapper.getClassName | private function getClassName()
{
if (null === $this->className) {
$this->className = get_class($this);
}
return $this->className;
} | php | private function getClassName()
{
if (null === $this->className) {
$this->className = get_class($this);
}
return $this->className;
} | Returns current class name
@return string | https://github.com/adrenalinkin/enum-mapper/blob/3385e6cdf75f7f9863cd3222ece76de1a3e5961d/Mapper/AbstractEnumMapper.php#L203-L210 |
adrenalinkin/enum-mapper | Mapper/AbstractEnumMapper.php | AbstractEnumMapper.getConstants | private function getConstants()
{
if (empty($this->constants)) {
try {
$reflection = new \ReflectionClass($this->getClassName());
$this->constants = $reflection->getConstants();
} catch (\ReflectionException $e) {
$this->constants = [];
}
}
return $this->constants;
} | php | private function getConstants()
{
if (empty($this->constants)) {
try {
$reflection = new \ReflectionClass($this->getClassName());
$this->constants = $reflection->getConstants();
} catch (\ReflectionException $e) {
$this->constants = [];
}
}
return $this->constants;
} | Returns list of the all available constants of the current class
@return array | https://github.com/adrenalinkin/enum-mapper/blob/3385e6cdf75f7f9863cd3222ece76de1a3e5961d/Mapper/AbstractEnumMapper.php#L217-L229 |
wartw98/core | Payment/Method.php | Method.setInfoInstance | final function setInfoInstance(II $i) {
$this->_ii = $i;
/**
* 2017-03-14
* Сюда мы попадаем, в частности, из:
* 1) @used-by \Magento\Quote\Model\Quote\Payment::getMethodInstance()
* 2) @used-by \Magento\Sales\Model\Order\Payment::getMethodInstance()
* Метод №1 устанавливает платёжному методу магазин,
* в то время как метод №2 — не устанавливает.
* По этой причине, если $info имеет класс @see \Magento\Sales\Model\Order\Payment,
* то устанавливаем магазин платёжному методу вручную.
*/
if ($i instanceof OP) {
$this->setStore($i->getOrder()->getStoreId());
}
} | php | final function setInfoInstance(II $i) {
$this->_ii = $i;
/**
* 2017-03-14
* Сюда мы попадаем, в частности, из:
* 1) @used-by \Magento\Quote\Model\Quote\Payment::getMethodInstance()
* 2) @used-by \Magento\Sales\Model\Order\Payment::getMethodInstance()
* Метод №1 устанавливает платёжному методу магазин,
* в то время как метод №2 — не устанавливает.
* По этой причине, если $info имеет класс @see \Magento\Sales\Model\Order\Payment,
* то устанавливаем магазин платёжному методу вручную.
*/
if ($i instanceof OP) {
$this->setStore($i->getOrder()->getStoreId());
}
} | 2016-02-12
@override
How is a payment method's setInfoInstance() used? https://mage2.pro/t/697
2017-03-30
Каждый потомок Method является объектом-одиночкой: @see _s(),
но вот info instance в него может устанавливаться разный: @see setInfoInstance()
Так происходит, например, в методе @see \Df\Payment\Observer\DataProvider\SearchResult::execute()
https://github.com/mage2pro/core/blob/2.4.13/Payment/Observer/DataProvider/SearchResult.php#L52-L65
Аналогично, в Method может устанавливаться разный store: @see setStore()
Поэтому будьте осторожны с кэшированием внутри Method!
@used-by getInfoInstance()
@param II|I|OP|QP $i | https://github.com/wartw98/core/blob/e1f44f6b4798a7b988f6a1cae639ff3745c9cd2a/Payment/Method.php#L1609-L1624 |
wartw98/core | Payment/Method.php | Method.tidFormat | final function tidFormat(T $t, $e = false) {
/** @var string $id */
$id = $t->getTxnId();
return df_tag_if(!$e ? $id : $this->tid()->i2e($id), $url = $this->transUrl($t), 'a', [
/** @var string|null $url */
'href' => $url, 'target' => '_blank', 'title' => __(
'View the transaction in the %1 interface', $this->getTitle()
)
]);
} | php | final function tidFormat(T $t, $e = false) {
/** @var string $id */
$id = $t->getTxnId();
return df_tag_if(!$e ? $id : $this->tid()->i2e($id), $url = $this->transUrl($t), 'a', [
/** @var string|null $url */
'href' => $url, 'target' => '_blank', 'title' => __(
'View the transaction in the %1 interface', $this->getTitle()
)
]);
} | 2016-08-20
@used-by \Df\Payment\Block\Info::siID()
@used-by \Df\Payment\Observer\FormatTransactionId::execute()
@param T $t
@param bool $e [optional]
@return string | https://github.com/wartw98/core/blob/e1f44f6b4798a7b988f6a1cae639ff3745c9cd2a/Payment/Method.php#L1713-L1722 |
ttools/ttools | src/TTools/TTools.php | TTools.getAuthorizeUrl | public function getAuthorizeUrl(array $params = [])
{
$result = $this->OAuthRequest(self::API_BASE . self::REQUEST_PATH, $params);
if ($result->getCode() == 200) {
$tokens = $this->parseResponse($result->getResponse());
return [
'auth_url' => self::API_BASE . $this->auth_method . '?oauth_token=' . $tokens['oauth_token'],
'secret' => $tokens['oauth_token_secret'],
'token' => $tokens['oauth_token']
];
}
return $this->handleError($result);
} | php | public function getAuthorizeUrl(array $params = [])
{
$result = $this->OAuthRequest(self::API_BASE . self::REQUEST_PATH, $params);
if ($result->getCode() == 200) {
$tokens = $this->parseResponse($result->getResponse());
return [
'auth_url' => self::API_BASE . $this->auth_method . '?oauth_token=' . $tokens['oauth_token'],
'secret' => $tokens['oauth_token_secret'],
'token' => $tokens['oauth_token']
];
}
return $this->handleError($result);
} | Gets the authorization url.
@param array $params Custom parameters passed to the OAuth request
@return array If successful, returns an array with 'auth_url', 'secret' and 'token';
otherwise, returns an array with error code and message. | https://github.com/ttools/ttools/blob/32e6b1d9ffa346db3bbfff46a258f12d0c322819/src/TTools/TTools.php#L77-L93 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.