sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function add(UserEntity $user)
{
$id = $user->getUserId();
$this->users[$id] = $user;
parent::markAdded($id);
} | {@inheritDoc} | entailment |
public function create($userId, $username, $password, $email)
{
return new UserEntity((int)$userId, $username, $password, $email);
} | {@inheritDoc} | entailment |
public function findOneByEmail($email)
{
foreach ($this->users as $user) {
if ($user->getEmail() === $email) {
return $user;
}
}
$result = $this->getQueryBuilder()
->where('u.email = :email')
->setParameter(':email', $email)
->execute();
$row = $result->fetch(\PDO::FETCH_OBJ);
if (!$row) {
return null;
}
$entity = $this->rowToEntity($row);
$this->replace($entity);
return $entity;
} | {@inheritDoc} | entailment |
public function findOneByUsername($username)
{
foreach ($this->users as $user) {
if ($user->getUsername() === $username) {
return $user;
}
}
$result = $this->getQueryBuilder()
->where('u.username = :username')
->setParameter(':username', $username)
->execute();
$row = $result->fetch(\PDO::FETCH_OBJ);
if (!$row) {
return null;
}
$entity = $this->rowToEntity($row);
$this->replace($entity);
return $entity;
} | {@inheritDoc} | entailment |
public function getUniqueId()
{
$result = $this->db->prepare("SELECT MAX(user_id) FROM users");
$result->execute();
$row = $result->fetchColumn();
$row += count($this->users);
$row -= count(parent::getDeleted());
return (int)($row + 1);
} | {@inheritDoc} | entailment |
public function replace(UserEntity $user)
{
$id = $user->getUserId();
$this->users[$id] = $user;
parent::markModified($id);
} | {@inheritDoc} | entailment |
public function sync()
{
foreach (parent::getDeleted() as $id) {
if (isset($this->users[$id])) {
$this->db->delete('users', array('user_id' => $id));
unset($this->users[$id]);
parent::reassign($id);
}
}
foreach (parent::getAdded() as $id) {
if (isset($this->users[$id])) {
$user = $this->users[$id];
$this->db->insert('users', $this->entityToRow($user));
parent::reassign($id);
}
}
foreach (parent::getModified() as $id) {
if (isset($this->users[$id])) {
$user = $this->users[$id];
$this->db->update('users', $this->entityToRow($user), array('user_id' => $id));
parent::reassign($id);
}
}
} | {@inheritDoc} | entailment |
public function bootstrapGlyphiconFunction(array $args = []) {
return $this->bootstrapGlyphicon(ArrayHelper::get($args, "name", "home"), ArrayHelper::get($args, "style"));
} | Displays a Bootstrap glyphicon.
@param array $args The arguments.
@return string Returns the Bootstrap glyphicon. | entailment |
public function handle(ServerRequestInterface $request)
{
$clientIpAddress = $request->getClientIpAddress();
$debugIpAddresses = config('ipAddresses')->offsetGet('debug');
if (in_array($clientIpAddress, $debugIpAddresses)) {
$_ENV[ 'DEBUG_STAGE' ] = 'DEVELOPER';
error_reporting(-1);
ini_set('display_errors', 1);
if (isset($_REQUEST[ 'PHP_INFO' ])) {
phpinfo();
exit(EXIT_SUCCESS);
}
} else {
ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
}
} | Environment::handle
Handles a request and produces a response
May call other collaborating code to generate the response.
@param \O2System\Psr\Http\Message\ServerRequestInterface $request | entailment |
public function setToggle($label)
{
if ($label instanceof Button) {
$this->toggle = $label;
} else {
$this->toggle = new Button($label);
$this->entity->setEntityName($label);
}
$this->toggle->attributes->addAttribute('data-toggle', 'dropdown');
$this->toggle->attributes->addAttribute('aria-haspopup', true);
$this->toggle->attributes->addAttribute('aria-expanded', false);
$this->toggle->attributes->addAttributeClass('dropdown-toggle');
return $this;
} | Dropdown::setToggle
@param string|Button $label
@return static | entailment |
public function splitMenu()
{
$this->attributes->removeAttributeClass('dropdown');
$this->attributes->addAttributeClass('btn-group');
$textContent = clone $this->toggle->textContent;
$childNodes = clone $this->toggle->childNodes;
$attributes = $this->toggle->attributes;
$this->toggle = new Button();
$buttonAttributes = clone $attributes;
$buttonAttributes->removeAttributeClass('dropdown-toggle');
$buttonAttributes->removeAttribute(['data-*', 'aria-*']);
$this->toggle->attributes = $buttonAttributes;
$this->toggle->textContent = $textContent;
$this->toggleButton = new Button();
$this->toggleButton->attributes = $attributes;
$this->toggleButton->childNodes = $childNodes;
$srOnly = new Element('span');
$srOnly->attributes->addAttributeClass('sr-only');
$srOnly->textContent->push('Toggle Dropdown');
$this->toggleButton->childNodes->append($srOnly);
return $this;
} | Dropdown::splitMenu
@return static | entailment |
public function render()
{
$output[] = $this->open();
$output[] = $this->toggle;
if ($this->toggleButton instanceof Button) {
$output[] = $this->toggleButton;
}
$output[] = $this->menu;
$output[] = $this->close();
return implode(PHP_EOL, $output);
} | Dropdown::render
@return string | entailment |
public function getUrl($realPath)
{
if (strpos($realPath, 'http') !== false) {
return $realPath;
}
return (new Uri())
->withQuery(null)
->withSegments(
new Uri\Segments(
str_replace(
[PATH_PUBLIC, DIRECTORY_SEPARATOR],
['', '/'],
$realPath
)
)
)
->__toString();
} | AbstractPosition::getUrl
@param string $realPath
@return string | entailment |
public function loadCollections(array $collections)
{
foreach ($collections as $subDir => $files) {
if (is_array($files) and count($files)) {
// normalize the subDirectory with a trailing separator
$subDir = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $subDir);
$subDir = rtrim($subDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
foreach ($files as $file) {
if (strpos($file, 'http') !== false) {
$this->loadUrl($file, $subDir);
} else {
$this->loadFile($file, $subDir);
}
}
} elseif (is_string($files)) {
$this->loadFile($files);
}
}
} | AbstractPosition::loadCollections
@param array $collections | entailment |
public function loadUrl($url, $subDir = null)
{
$property = is_null($subDir) ? 'css' : null;
if (is_null($property)) {
switch ($subDir) {
default:
case 'css/':
$property = 'css';
break;
case 'font/':
case 'fonts/':
$property = 'font';
break;
case 'js/':
$property = 'javascript';
break;
}
}
if (property_exists($this, $property)) {
if ( ! call_user_func_array([$this->{$property}, 'has'], [$url])) {
$this->{$property}->append($url);
return true;
}
}
return false;
} | AbstractPosition::loadUrl
@param string $url
@param string|null $subDir
@return bool | entailment |
protected function publishFile($filePath)
{
$publicFilePath = str_replace(PATH_RESOURCES, PATH_PUBLIC, $filePath);
$publicFileDir = dirname($publicFilePath) . DIRECTORY_SEPARATOR;
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
$publicMinifyFilePath = str_replace('.' . $extension, '.min.' . $extension, $publicFilePath);
$fileContent = file_get_contents($filePath);
$fileVersion = $this->getVersion($fileContent);
if (is_file($mapFilePath = $publicFilePath . '.map')) {
$mapMetadata = json_decode(file_get_contents($mapFilePath), true);
// if the file version is changed delete it first
if ( ! hash_equals($fileVersion, $mapMetadata[ 'version' ])) {
unlink($publicFilePath);
unlink($publicMinifyFilePath);
unlink($mapFilePath);
}
}
if ( ! is_file($mapFilePath)) {
if ( ! empty($fileContent)) {
$mapMetadata = [
'version' => $fileVersion,
'sources' => [
$filePath,
],
'names' => [],
'mappings' => [],
'file' => pathinfo($publicMinifyFilePath, PATHINFO_BASENAME),
'sourcesContent' => [
$fileContent,
],
'sourceRoot' => '',
];
if ( ! is_dir($publicFileDir)) {
@mkdir($publicFileDir, 0777, true);
}
if (is_writable($publicFileDir)) {
if ($fileStream = @fopen($publicFilePath, 'ab')) {
flock($fileStream, LOCK_EX);
fwrite($fileStream, $fileContent);
flock($fileStream, LOCK_UN);
fclose($fileStream);
// File Map
if ($fileStream = @fopen($mapFilePath, 'ab')) {
flock($fileStream, LOCK_EX);
fwrite($fileStream, json_encode($mapMetadata));
flock($fileStream, LOCK_UN);
fclose($fileStream);
}
switch ($extension) {
case 'min.css':
case 'css':
$minifyStyleHandler = new CSS($publicFilePath);
$minifyStyleHandler->minify($publicMinifyFilePath);
break;
case 'min.js':
case 'js':
$minifyJavascriptHandler = new JS($publicFilePath);
$minifyJavascriptHandler->minify($publicMinifyFilePath);
break;
}
}
}
}
}
return [
'filePath' => $publicFilePath,
'url' => $this->getUrl($publicFilePath),
'minify' => [
'filePath' => $publicMinifyFilePath,
'url' => $this->getUrl($publicMinifyFilePath),
],
'version' => $fileVersion,
];
} | AbstractPosition::publishFile
@param $filePath
@return array | entailment |
protected function bundleFile($filename, array $sources)
{
$sourcesContent = [];
foreach ($sources as $key => $source) {
$content = file_get_contents($source);
if ( ! empty($content)) {
$sourcesContent[] = $content;
} else {
unset($sources[ $key ]);
}
}
$fileContent = implode(PHP_EOL, $sourcesContent);
$fileVersion = $this->getVersion($fileContent);
$publicFilePath = PATH_PUBLIC . $filename;
$filename = pathinfo($publicFilePath, PATHINFO_BASENAME);
$publicFileDir = dirname($publicFilePath) . DIRECTORY_SEPARATOR . 'bundled' . DIRECTORY_SEPARATOR;
$publicFilePath = $publicFileDir . $filename;
$extension = pathinfo($publicFilePath, PATHINFO_EXTENSION);
$publicMinifyFilePath = str_replace('.' . $extension, '.min.' . $extension, $publicFilePath);
if ( ! empty($sourcesContent)) {
if (is_file($mapFilePath = $publicFilePath . '.map')) {
$mapMetadata = json_decode(file_get_contents($mapFilePath), true);
// if the file version is changed delete it first
if ( ! hash_equals($fileVersion, $mapMetadata[ 'version' ])) {
unlink($publicFilePath);
unlink($publicMinifyFilePath);
unlink($mapFilePath);
}
}
if ( ! is_file($mapFilePath)) {
if ( ! empty($fileContent)) {
$mapMetadata = [
'version' => $fileVersion,
'sources' => $sources,
'names' => [],
'mappings' => [],
'file' => pathinfo($publicMinifyFilePath, PATHINFO_BASENAME),
'sourcesContent' => $sourcesContent,
'sourceRoot' => '',
];
if ( ! is_writable($publicFileDir)) {
@mkdir($publicFileDir, 0777, true);
}
if (is_writable($publicFileDir)) {
if ($fileStream = @fopen($publicFilePath, 'ab')) {
flock($fileStream, LOCK_EX);
fwrite($fileStream, $fileContent);
flock($fileStream, LOCK_UN);
fclose($fileStream);
// File Map
if ($fileStream = @fopen($mapFilePath, 'ab')) {
flock($fileStream, LOCK_EX);
fwrite($fileStream, json_encode($mapMetadata));
flock($fileStream, LOCK_UN);
fclose($fileStream);
}
switch ($extension) {
case 'min.css':
case 'css':
$minifyStyleHandler = new CSS($publicFilePath);
$minifyStyleHandler->minify($publicMinifyFilePath);
break;
case 'min.js':
case 'js':
$minifyJavascriptHandler = new JS($publicFilePath);
$minifyJavascriptHandler->minify($publicMinifyFilePath);
break;
}
}
}
}
}
}
return [
'filePath' => $publicFilePath,
'url' => $this->getUrl($publicFilePath),
'minify' => [
'filePath' => $publicMinifyFilePath,
'url' => $this->getUrl($publicMinifyFilePath),
],
'version' => $fileVersion,
];
} | AbstractPosition::bundleFile
@param string $filename
@param array $sources
@return array | entailment |
protected function getFilePath($filename, $subDir = null)
{
$directories = presenter()->assets->getFilePaths();
foreach ($directories as $directory) {
/**
* Try with sub directory
* find from public directory first then resource directory
*/
if (isset($subDir)) {
$subDir = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $subDir);
if (is_file($filePath = str_replace(PATH_RESOURCES, PATH_PUBLIC,
$directory) . $subDir . $filename)) {
return $filePath;
break;
} elseif (is_file($filePath = str_replace(PATH_RESOURCES, PATH_PUBLIC . 'assets' . DIRECTORY_SEPARATOR,
$directory) . $subDir . $filename)) {
return $filePath;
break;
} elseif (is_file($filePath = $directory . $subDir . $filename)) {
return $filePath;
break;
}
}
/**
* Try without sub directory
* find from public directory first then resource directory
*/
if (is_file($filePath = str_replace(PATH_RESOURCES, PATH_PUBLIC, $directory) . $filename)) {
return $filePath;
break;
} elseif (is_file($filePath = str_replace(PATH_RESOURCES, PATH_PUBLIC . 'assets' . DIRECTORY_SEPARATOR,
$directory) . $filename)) {
return $filePath;
break;
} elseif (is_file($filePath = $directory . $filename)) {
return $filePath;
break;
}
}
return false;
} | AbstractPosition::getFilePath
@param string $filename
@param string|null $subDir
@return string | entailment |
public function getVersion($codeSerialize)
{
$codeMd5 = md5($codeSerialize);
$strSplit = str_split($codeMd5, 4);
foreach ($strSplit as $strPart) {
$strInt[] = str_pad(hexdec($strPart), 5, '0', STR_PAD_LEFT);
}
$codeVersion = round(implode('', $strInt), 10);
return substr_replace($codeVersion, '.', 3, strlen($codeVersion) - 5);
} | AbstractPosition::getVersion
@param string $code
@return string | entailment |
private function message(string $expectedRowCount, int $actualRowCount, string $query): string
{
$query = trim($query);
$message = 'Wrong number of rows selected.';
$message .= "\n";
$message .= sprintf("Expected number of rows: %s.\n", $expectedRowCount);
$message .= sprintf("Actual number of rows: %s.\n", $actualRowCount);
$message .= 'Query:';
$message .= (strpos($query, "\n")!==false) ? "\n" : ' ';
$message .= $query;
return $message;
} | Composes the exception message.
@param string $expectedRowCount The expected number of rows selected.
@param int $actualRowCount The actual number of rows selected.
@param string $query The SQL query.
@return string | entailment |
public function createBlock()
{
$this->childNodes->push(new Body());
return $this->block = $this->childNodes->last();
} | Card::createBlock
@return Body | entailment |
public function show()
{
$this->block->collapse->attributes->removeAttributeClass('hide');
$this->block->collapse->attributes->addAttributeClass('show');
return $this;
} | Card::show
@return static | entailment |
public function hide()
{
$this->block->collapse->attributes->removeAttributeClass('show');
$this->block->collapse->attributes->addAttributeClass('hide');
return $this;
} | Card::hide
@return static | entailment |
public function render()
{
$output[] = $this->open();
if ($this->header->hasTextContent() || $this->header->hasChildNodes()) {
$output[] = $this->header;
}
if ($this->hasChildNodes()) {
$output[] = implode(PHP_EOL, $this->childNodes->getArrayCopy());
}
if ($this->footer->hasTextContent() || $this->footer->hasChildNodes()) {
$output[] = $this->footer;
}
$output[] = $this->close();
return implode(PHP_EOL, $output);
} | Card::render
@return string | entailment |
public static function getWikiViews() {
$tableContents = [];
$tableContents[] = new WikiView("Twig-extension", "CSS", "button", "Button");
$tableContents[] = new WikiView("twig-extension", "CSS", "code", "Code");
$tableContents[] = new WikiView("Twig-extension", "CSS", "grid", "Grid");
$tableContents[] = new WikiView("Twig-extension", "CSS", "image", "Image");
$tableContents[] = new WikiView("Twig-extension", "CSS", "typography", "Typography");
$tableContents[] = new WikiView("Twig-extension", "Component", "alert", "Alert");
$tableContents[] = new WikiView("Twig-extension", "Component", "badge", "Badge");
$tableContents[] = new WikiView("Twig-extension", "Component", "glyphicon", "Glyphicon");
$tableContents[] = new WikiView("Twig-extension", "Component", "label", "Label");
$tableContents[] = new WikiView("Twig-extension", "Component", "progress-bar", "Progress bar");
$tableContents[] = new WikiView("Twig-extension", "Utility", "form-button", "Form button");
$tableContents[] = new WikiView("Twig-extension", "Utility", "role-label", "Role label");
$tableContents[] = new WikiView("Twig-extension", "Utility", "table-button", "Table button");
$tableContents[] = new WikiView("Twig-extension", "Plugin", "font-awesome", "Font Awesome");
$tableContents[] = new WikiView("Twig-extension", "Plugin", "jquery-inputmask", "jQuery InputMask");
$tableContents[] = new WikiView("Twig-extension", "Plugin", "material-design-iconic-font", "Material Design Iconic Font");
$tableContents[] = new WikiView("Twig-extension", "Plugin", "meteocons", "Meteocons");
foreach ($tableContents as $current) {
$current->setBundle("WBWBootstrap");
}
return $tableContents;
} | Get the wiki views.
@return WikiView[] Returns the wiki views. | entailment |
public function indexAction($category, $package, $page) {
$wikiViews = self::getWikiViews();
$wikiView = WikiView::find($wikiViews, $category, $package, $page);
if (null === $wikiView) {
// Set a default wiki view.
$wikiView = $wikiViews[0];
$this->notifyDanger("The requested page was not found");
$this->notifyInfo("You have been redirected to homepage");
}
return $this->render($wikiView->getView(), [
"wikiViews" => $wikiViews,
"wikiView" => $wikiView,
"syntaxHighlighterConfig" => $this->getSyntaxHighlighterConfig(),
"syntaxHighlighterDefaults" => $this->getSyntaxHighlighterDefaults(),
"user" => $this->getSampleUser(),
"userRoleColors" => $this->getSampleUserRoleColors(),
"userRoleTranslations" => $this->getSampleUserRoleTranslations(),
]);
} | Displays a wiki page.
@param string $category The category.
@param string $package The parent.
@param string $page The page.
@return Response Returns the response. | entailment |
public function bootstrapButtonDangerFunction(array $args = []) {
return $this->bootstrapButton(ButtonFactory::parseDangerButton($args), ArrayHelper::get($args, "icon"));
} | Displays a Bootstrap button "Danger".
@param array $args The arguments.
@return string Returns the Bootstrap button "Danger". | entailment |
public function bootstrapButtonDefaultFunction(array $args = []) {
return $this->bootstrapButton(ButtonFactory::parseDefaultButton($args), ArrayHelper::get($args, "icon"));
} | Displays a Bootstrap button "Default".
@param array $args The arguments.
@return string Returns the Bootstrap button "Default". | entailment |
public function bootstrapButtonInfoFunction(array $args = []) {
return $this->bootstrapButton(ButtonFactory::parseInfoButton($args), ArrayHelper::get($args, "icon"));
} | Displays a Bootstrap button "Info".
@param array $args The arguments.
@return string Returns the Bootstrap button "Info". | entailment |
public function bootstrapButtonLinkFilter($button, $href = self::DEFAULT_HREF, $target = null) {
if (1 === preg_match("/disabled=\"disabled\"/", $button)) {
$searches = [" disabled=\"disabled\"", "class=\""];
$replaces = ["", "class=\"disabled "];
$button = StringHelper::replace($button, $searches, $replaces);
}
$searches = ["<button", "type=\"button\"", "</button>"];
$replaces = ["<a", "href=\"" . $href . "\"" . (null !== $target ? " target=\"" . $target . "\"" : ""), "</a>"];
return StringHelper::replace($button, $searches, $replaces);
} | Transforms a Bootstrap button into an anchor.
@param string $button The button.
@param string $href The href attribute.
@param string $target The target attribute.
@return string Returns the Bootstrap button transformed into an anchor. | entailment |
public function bootstrapButtonLinkFunction(array $args = []) {
return $this->bootstrapButton(ButtonFactory::parseLinkButton($args), ArrayHelper::get($args, "icon"));
} | Displays a Bootstrap button "Link".
@param array $args The arguments.
@return string Returns the Bootstrap button "Link". | entailment |
public function bootstrapButtonPrimaryFunction(array $args = []) {
return $this->bootstrapButton(ButtonFactory::parsePrimaryButton($args), ArrayHelper::get($args, "icon"));
} | Displays a Bootstrap button "Primary".
@param array $args The arguments.
@return string Returns the Bootstrap button "Primary". | entailment |
public function bootstrapButtonSuccessFunction(array $args = []) {
return $this->bootstrapButton(ButtonFactory::parseSuccessButton($args), ArrayHelper::get($args, "icon"));
} | Displays a Bootstrap button "Success".
@param array $args The arguments.
@return string Returns the Bootstrap button "Success". | entailment |
public function bootstrapButtonWarningFunction(array $args = []) {
return $this->bootstrapButton(ButtonFactory::parseWarningButton($args), ArrayHelper::get($args, "icon"));
} | Displays a Bootstrap button "Warning".
@param array $args The arguments.
@return string Returns the Bootstrap button "Warning". | entailment |
protected function getDefaultCommands()
{
// Keep the core default commands to have the HelpCommand which is used when using the --help option
$defaultCommands = parent::getDefaultCommands();
$defaultCommands[] = new ConstantsCommand();
$defaultCommands[] = new CrudCommand();
$defaultCommands[] = new NonStaticCommand();
$defaultCommands[] = new RoutineLoaderCommand();
$defaultCommands[] = new RoutineWrapperGeneratorCommand();
$defaultCommands[] = new StratumCommand();
return $defaultCommands;
} | Gets the default commands that should always be available.
@return Command[] An array of default Command instances | entailment |
public function getToken(string $token)
{
/* @var \ZfrOAuth2\Server\Model\AbstractToken $tokenFromDb */
$tokenFromDb = $this->tokenRepository->findByToken($token);
// Because the collation is most often case insensitive, we need to add a check here to ensure
// that the token matches case
if (! $tokenFromDb || ! hash_equals($tokenFromDb->getToken(), $token)) {
return null;
}
return $tokenFromDb;
} | Get a token using its identifier (the token itself)
@param string $token
@return AbstractToken|null | entailment |
protected function validateTokenScopes(array $scopes)
{
$scopes = array_map(function ($scope) {
return (string) $scope;
}, $scopes);
$registeredScopes = $this->scopeService->getAll();
$registeredScopes = array_map(function ($scope) {
return (string) $scope;
}, $registeredScopes);
$diff = array_diff($scopes, $registeredScopes);
if (count($diff) > 0) {
throw OAuth2Exception::invalidScope(sprintf(
'Some scope(s) do not exist: %s',
implode(', ', $diff)
));
}
} | Validate the token scopes against the registered scope
@param string[]|Scope[] $scopes
@throws OAuth2Exception (invalid_scope) When one or more of the given scopes where not registered | entailment |
public function setLabel($label)
{
$this->textContent->prepend($label);
$this->entity->setEntityName($label);
return $this;
} | Button::setLabel
@param string $label
@return static | entailment |
public function setIcon($icon)
{
if ($icon instanceof Icon) {
$this->icon = $icon;
} else {
$this->icon = new Icon($icon);
}
return $this;
} | Button::setIcon
@param string $icon
@return static | entailment |
public function render()
{
if ($this->icon instanceof Icon && $this->hasTextContent()) {
$this->attributes->addAttributeClass('btn-icon');
}
$output[] = $this->open();
if ($this->hasTextContent()) {
$output[] = implode('', $this->textContent->getArrayCopy());
}
if ($this->hasChildNodes()) {
$output[] = implode(PHP_EOL, $this->childNodes->getArrayCopy());
}
if ($this->icon instanceof Icon) {
$output[] = $this->icon;
}
$output[] = $this->close();
return implode(PHP_EOL, $output);
} | Button::render
@return string | entailment |
public function save(DomainObjectInterface &$domainObject): void
{
if ($domainObject->getId() === 0) {
$this->concreteInsert($domainObject);
}
$this->concreteUpdate($domainObject);
} | Store the DomainObject in persistent storage. Either insert
or update the store as required.
@param DomainObjectInterface $domainObject
@return void | entailment |
public function gc($maxlifetime)
{
$this->pdo->queryWithParam(
'DELETE FROM session WHERE last_update < DATE_SUB(NOW(), INTERVAL :maxlifetime SECOND)',
[[':maxlifetime', $maxlifetime, \PDO::PARAM_INT]]
);
return $this->pdo->getLastOperationStatus();
} | Delete old sessions from storage.
http://php.net/manual/en/sessionhandler.gc.php.
@param int $maxlifetime
@return bool | entailment |
public function read($session_id)
{
//string casting is a fix for PHP 7
//when strict type are enable
return (string) $this->pdo->queryWithParam(
'SELECT session_data FROM session WHERE session_id = :session_id',
[[':session_id', $session_id, \PDO::PARAM_STR]]
)->fetchColumn();
} | Read session data from storage.
http://php.net/manual/en/sessionhandler.read.php.
@param string $session_id
@return string | entailment |
public function write($session_id, $session_data)
{
$this->pdo->queryWithParam(
'INSERT INTO session SET session_id = :session_id, session_data = :session_data ON DUPLICATE KEY UPDATE session_data = :session_data',
[
[':session_id', $session_id, \PDO::PARAM_STR],
[':session_data', $session_data, \PDO::PARAM_STR]
]
);
return $this->pdo->getLastOperationStatus();
} | Write session data to storage.
http://php.net/manual/en/sessionhandler.write.php.
@param string $session_id
@param string $session_data
@return bool | entailment |
public function destroy($session_id)
{
$this->pdo->queryWithParam(
'DELETE FROM session WHERE session_id = :session_id',
[[':session_id', $session_id, \PDO::PARAM_STR]]
);
return $this->pdo->getLastOperationStatus();
} | Destroy session data.
http://php.net/manual/en/sessionhandler.destroy.php.
@param string $session_id
@return bool | entailment |
public function index()
{
if (false !== ($manifest = $this->config->loadFile('manifest', true))) {
output()->sendPayload([
'short_name' => $manifest->shortName,
'name' => $manifest->name,
'description' => $manifest->description,
'icons' => array_values($manifest->icons),
'start_url' => empty($manifest->startUrl) ? '/' : $manifest->startUrl,
'display' => $manifest->display,
'orientation' => $manifest->orientation,
'theme_color' => $manifest->themeColor,
'background_color' => $manifest->backgroundColor,
'related_applications' => empty($manifest->relatedApplications) ? [] : $manifest->relatedApplications,
]);
}
} | Manifest::index | entailment |
public function bootstrapAlertDangerFunction(array $args = []) {
return $this->bootstrapAlert(ArrayHelper::get($args, "content"), ArrayHelper::get($args, "dismissible"), "alert-" . BootstrapInterface::BOOTSTRAP_DANGER);
} | Displays a Bootstrap alert "Danger".
@param array $args The arguments.
@return string Returns the Bootstrap alert "Danger". | entailment |
public function bootstrapAlertInfoFunction(array $args = []) {
return $this->bootstrapAlert(ArrayHelper::get($args, "content"), ArrayHelper::get($args, "dismissible"), "alert-" . BootstrapInterface::BOOTSTRAP_INFO);
} | Displays a Bootstrap alert "Info".
@param array $args The arguments.
@return string Returns the Bootstrap alert "Info". | entailment |
public function bootstrapAlertLinkFunction(array $args = []) {
$attributes = [];
$attributes["href"] = ArrayHelper::get($args, "href", NavigationInterface::NAVIGATION_HREF_DEFAULT);
$innerHTML = ArrayHelper::get($args, "content");
return static::coreHTMLElement("a", $innerHTML, $attributes);
} | Displays a Bootstrap alert "Link".
@param array $args The arguments.
@return string Returns the Bootstrap alert "Link". | entailment |
public function bootstrapAlertSuccessFunction(array $args = []) {
return $this->bootstrapAlert(ArrayHelper::get($args, "content"), ArrayHelper::get($args, "dismissible"), "alert-" . BootstrapInterface::BOOTSTRAP_SUCCESS);
} | Displays a Bootstrap alert "Success".
@param array $args The arguments.
@return string Returns the Bootstrap alert "Success". | entailment |
public function bootstrapAlertWarningFunction(array $args = []) {
return $this->bootstrapAlert(ArrayHelper::get($args, "content"), ArrayHelper::get($args, "dismissible"), "alert-" . BootstrapInterface::BOOTSTRAP_WARNING);
} | Displays a Bootstrap alert "Warning".
@param array $args The arguments.
@return string Returns the Bootstrap alert "Warning". | entailment |
public function getFunctions() {
return [
new TwigFunction("bootstrapAlertDanger", [$this, "bootstrapAlertDangerFunction"], ["is_safe" => ["html"]]),
new TwigFunction("bsAlertDanger", [$this, "bootstrapAlertDangerFunction"], ["is_safe" => ["html"]]),
new TwigFunction("bootstrapAlertInfo", [$this, "bootstrapAlertInfoFunction"], ["is_safe" => ["html"]]),
new TwigFunction("bsAlertInfo", [$this, "bootstrapAlertInfoFunction"], ["is_safe" => ["html"]]),
new TwigFunction("bootstrapAlertLink", [$this, "bootstrapAlertLinkFunction"], ["is_safe" => ["html"]]),
new TwigFunction("bsAlertLink", [$this, "bootstrapAlertLinkFunction"], ["is_safe" => ["html"]]),
new TwigFunction("bootstrapAlertSuccess", [$this, "bootstrapAlertSuccessFunction"], ["is_safe" => ["html"]]),
new TwigFunction("bsAlertSuccess", [$this, "bootstrapAlertSuccessFunction"], ["is_safe" => ["html"]]),
new TwigFunction("bootstrapAlertWarning", [$this, "bootstrapAlertWarningFunction"], ["is_safe" => ["html"]]),
new TwigFunction("bsAlertWarning", [$this, "bootstrapAlertWarningFunction"], ["is_safe" => ["html"]]),
];
} | Get the Twig functions.
@return TwigFunction[] Returns the Twig functions. | entailment |
public function getFromRandom(int $length): string
{
$password = [];
while ($length) {
$password[] = $this->getRandomChar($this->chars[\random_int(0, 3)]);
$length--;
}
return \implode($password);
} | Generate a random password.
<pre><code class="php">use Linna\Auth\PasswordGenerator;
$passwordGenerator = new PasswordGenerator();
$random = $passwordGenerator->getFromRandom(20);
//var_dump result
//r4Q,1J*tM7D_99q0u>61
var_dump($random);
</code></pre>
@param int $length Desiderated password length.
@return string Random password. | entailment |
public function getTopology(string $password): string
{
$array = \str_split($password);
$topology = [];
foreach ($array as $char) {
$topology[] = $this->getTopologyGroup($char);
}
return \implode($topology);
} | Return topology for given password.
<pre><code class="php">use Linna\Auth\PasswordGenerator;
$passwordGenerator = new PasswordGenerator();
$topology = $passwordGenerator->getTopology('r4Q,1J*tM7D_99q0u>61');
//var_dump result
//ldusdusludusddldlsdd
var_dump($topology);
</code></pre>
@param string $password Password.
@return string Topology for the argument passed password. | entailment |
private function getTopologyGroup(string $char): string
{
$groups = $this->chars;
if (\strpos($groups[0], $char) !== false) {
return 'u';
}
if (\strpos($groups[1], $char) !== false) {
return 'l';
}
if (\strpos($groups[2], $char) !== false) {
return 'd';
}
if (\strpos($groups[3], $char) !== false) {
return 's';
}
throw new InvalidArgumentException('Out of group character provided.');
} | Return topology group for the given char.
@param string $char
@return string
@throws InvalidArgumentException If char provided isn't inside any group | entailment |
public function getFromTopology(string $topology): string
{
$array = \str_split(\strtolower($topology));
$groups = [117 => 0, 108 => 1, 100 => 2, 115 => 3];
$password = [];
foreach ($array as $char) {
$int = \ord($char);
if (isset($groups[$int])) {
$password[] = $this->getRandomChar($this->chars[$groups[$int]]);
continue;
}
throw new InvalidArgumentException('Invalid pattern provided, accepted only u, l, d and s.');
}
return \implode($password);
} | Generate a random password corresponding at the given topology.
<pre><code class="php">use Linna\Auth\PasswordGenerator;
$passwordGenerator = new PasswordGenerator();
$random = $passwordGenerator->getFromTopology('ldusdusludusddldlsdd');
//var_dump result
//r4Q,1J*tM7D_99q0u>61
var_dump($random);
</code></pre>
@param string $topology Topology for generate password.
@return string Random password corresponding the given topology.
@throws InvalidArgumentException If invalid pattern is provided. | entailment |
private function getRandomChar(string $interval): string
{
$size = \strlen($interval) - 1;
$int = \random_int(0, $size);
return $interval[$int];
} | Get random char between.
@param string $interval
@return string | entailment |
public function begin(): void
{
$ret = $this->mysqli->autocommit(false);
if (!$ret) $this->mySqlError('mysqli::autocommit');
} | Starts a transaction.
Wrapper around [mysqli::autocommit](http://php.net/manual/mysqli.autocommit.php), however on failure an exception
is thrown.
@since 1.0.0
@api | entailment |
public function connect(string $host, string $user, string $password, string $database, int $port = 3306): void
{
$this->mysqli = new \mysqli($host, $user, $password, $database, $port);
if ($this->mysqli->connect_errno)
{
$message = 'MySQL Error no: '.$this->mysqli->connect_errno."\n";
$message .= str_replace('%', '%%', $this->mysqli->connect_error);
$message .= "\n";
throw new RuntimeException($message);
}
// Set the options.
foreach ($this->options as $option => $value)
{
$this->mysqli->options($option, $value);
}
// Set the default character set.
$ret = $this->mysqli->set_charset($this->charSet);
if (!$ret) $this->mySqlError('mysqli::set_charset');
// Set the SQL mode.
$this->executeNone("set sql_mode = '".$this->sqlMode."'");
// Set transaction isolation level.
$this->executeNone("set session tx_isolation = '".$this->transactionIsolationLevel."'");
// Set flag to use method mysqli_result::fetch_all if we are using MySQL native driver.
$this->haveFetchAll = method_exists('mysqli_result', 'fetch_all');
} | Connects to a MySQL instance.
Wrapper around [mysqli::__construct](http://php.net/manual/mysqli.construct.php), however on failure an exception
is thrown.
@param string $host The hostname.
@param string $user The MySQL user name.
@param string $password The password.
@param string $database The default database.
@param int $port The port number.
@since 1.0.0
@api | entailment |
public function disconnect(): void
{
if ($this->mysqli!==null)
{
$this->mysqli->close();
$this->mysqli = null;
}
} | Closes the connection to the MySQL instance, if connected.
@since 1.0.0
@api | entailment |
public function executeLog(string $queries): int
{
// Counter for the number of rows written/logged.
$n = 0;
$this->multiQuery($queries);
do
{
$result = $this->mysqli->store_result();
if ($this->mysqli->errno) $this->mySqlError('mysqli::store_result');
if ($result)
{
$fields = $result->fetch_fields();
while (($row = $result->fetch_row()))
{
$line = '';
foreach ($row as $i => $field)
{
if ($i>0) $line .= ' ';
$line .= str_pad((string)$field, $fields[$i]->max_length);
}
echo date('Y-m-d H:i:s'), ' ', $line, "\n";
$n++;
}
$result->free();
}
$continue = $this->mysqli->more_results();
if ($continue)
{
$tmp = $this->mysqli->next_result();
if ($tmp===false) $this->mySqlError('mysqli::next_result');
}
} while ($continue);
return $n;
} | Executes a query and logs the result set.
@param string $queries The query or multi query.
@return int The total number of rows selected/logged.
@since 1.0.0
@api | entailment |
public function executeMulti(string $queries): array
{
$ret = [];
$this->multiQuery($queries);
do
{
$result = $this->mysqli->store_result();
if ($this->mysqli->errno) $this->mySqlError('mysqli::store_result');
if ($result)
{
if ($this->haveFetchAll)
{
$ret[] = $result->fetch_all(MYSQLI_ASSOC);
}
else
{
$tmp = [];
while (($row = $result->fetch_assoc()))
{
$tmp[] = $row;
}
$ret[] = $tmp;
}
$result->free();
}
else
{
$ret[] = $this->mysqli->affected_rows;
}
$continue = $this->mysqli->more_results();
if ($continue)
{
$tmp = $this->mysqli->next_result();
if ($tmp===false) $this->mySqlError('mysqli::next_result');
}
} while ($continue);
return $ret;
} | Executes multiple queries and returns an array with the "result" of each query, i.e. the length of the returned
array equals the number of queries. For SELECT, SHOW, DESCRIBE or EXPLAIN queries the "result" is the selected
rows (i.e. an array of arrays), for other queries the "result" is the number of effected rows.
@param string $queries The SQL statements.
@return array
@since 1.0.0
@api | entailment |
public function executeNone(string $query): int
{
$this->realQuery($query);
$n = $this->mysqli->affected_rows;
if ($this->mysqli->more_results()) $this->mysqli->next_result();
return $n;
} | Executes a query that does not select any rows.
@param string $query The SQL statement.
@return int The number of affected rows (if any).
@since 1.0.0
@api | entailment |
public function executeRow0(string $query): ?array
{
$result = $this->query($query);
$row = $result->fetch_assoc();
$n = $result->num_rows;
$result->free();
if ($this->mysqli->more_results()) $this->mysqli->next_result();
if (!($n==0 || $n==1))
{
throw new ResultException('0 or 1', $n, $query);
}
return $row;
} | Executes a query that returns 0 or 1 row.
Throws an exception if the query selects 2 or more rows.
@param string $query The SQL statement.
@return array|null The selected row.
@since 1.0.0
@api | entailment |
public function executeRows(string $query): array
{
$result = $this->query($query);
if ($this->haveFetchAll)
{
$ret = $result->fetch_all(MYSQLI_ASSOC);
}
else
{
$ret = [];
while (($row = $result->fetch_assoc()))
{
$ret[] = $row;
}
}
$result->free();
if ($this->mysqli->more_results()) $this->mysqli->next_result();
return $ret;
} | Executes a query that returns 0 or more rows.
@param string $query The SQL statement.
@return array[] The selected rows.
@since 1.0.0
@api | entailment |
public function executeTable(string $query): int
{
$row_count = 0;
$this->multiQuery($query);
do
{
$result = $this->mysqli->store_result();
if ($this->mysqli->errno) $this->mySqlError('mysqli::store_result');
if ($result)
{
$columns = [];
// Get metadata to array.
foreach ($result->fetch_fields() as $str_num => $column)
{
$columns[$str_num]['header'] = $column->name;
$columns[$str_num]['type'] = $column->type;
$columns[$str_num]['length'] = max(4, $column->max_length, mb_strlen($column->name));
}
// Show the table header.
$this->executeTableShowHeader($columns);
// Show for all rows all columns.
while (($row = $result->fetch_row()))
{
$row_count++;
// First row separator.
echo '|';
foreach ($row as $i => $value)
{
$this->executeTableShowTableColumn($columns[$i], $value);
echo '|';
}
echo "\n";
}
// Show the table footer.
$this->executeTableShowFooter($columns);
}
$continue = $this->mysqli->more_results();
if ($continue)
{
$tmp = $this->mysqli->next_result();
if ($tmp===false) $this->mySqlError('mysqli::next_result');
}
} while ($continue);
return $row_count;
} | Executes a query and shows the data in a formatted in a table (like mysql's default pager) of in multiple tables
(in case of a multi query).
@param string $query The query.
@return int The total number of rows in the tables.
@since 1.0.0
@api | entailment |
public function getMaxAllowedPacket(): int
{
if (!isset($this->maxAllowedPacket))
{
$query = "show variables like 'max_allowed_packet'";
$max_allowed_packet = $this->executeRow1($query);
$this->maxAllowedPacket = $max_allowed_packet['Value'];
// Note: When setting $chunkSize equal to $maxAllowedPacket it is not possible to transmit a LOB
// with size $maxAllowedPacket bytes (but only $maxAllowedPacket - 8 bytes). But when setting the size of
// $chunkSize less than $maxAllowedPacket than it is possible to transmit a LOB with size
// $maxAllowedPacket bytes.
$this->chunkSize = (int)min($this->maxAllowedPacket - 8, 1024 * 1024);
}
return (int)$this->maxAllowedPacket;
} | Returns the value of the MySQL variable max_allowed_packet.
@return int | entailment |
public function getRowInRowSet(string $columnName, $value, array $rowSet): array
{
if (is_array($rowSet))
{
foreach ($rowSet as $row)
{
if ((string)$row[$columnName]==(string)$value)
{
return $row;
}
}
}
throw new RuntimeException("Value '%s' for column '%s' not found in row set.", $value, $columnName);
} | Returns the first row in a row set for which a column has a specific value.
Throws an exception if now row is found.
@param string $columnName The column name (or in PHP terms the key in an row (i.e. array) in the row set).
@param mixed $value The value to be found.
@param array[] $rowSet The row set.
@return array
@since 1.0.0
@api | entailment |
public function quoteBit(?string $bits): string
{
if ($bits===null || $bits==='')
{
return 'null';
}
return "b'".$this->mysqli->real_escape_string($bits)."'";
} | Returns a literal for a bit value that can be safely used in SQL statements.
@param string|null $bits The bit value.
@return string | entailment |
public function quoteListOfInt($list, string $delimiter, string $enclosure, string $escape): string
{
if ($list===null || $list===false || $list==='' || $list===[])
{
return 'null';
}
$ret = '';
if (is_scalar($list))
{
$list = str_getcsv($list, $delimiter, $enclosure, $escape);
}
elseif (is_array($list))
{
// Nothing to do.
;
}
else
{
throw new RuntimeException("Unexpected parameter type '%s'. Array or scalar expected.", gettype($list));
}
foreach ($list as $number)
{
if ($list===null || $list===false || $list==='')
{
throw new RuntimeException('Empty values are not allowed.');
}
if (!is_numeric($number))
{
throw new RuntimeException("Value '%s' is not a number.", (is_scalar($number)) ? $number : gettype($number));
}
if ($ret) $ret .= ',';
$ret .= $number;
}
return $this->quoteString($ret);
} | Returns a literal for an expression with a separated list of integers that can be safely used in SQL
statements. Throws an exception if the value is a list of integers.
@param string|array $list The list of integers.
@param string $delimiter The field delimiter (one character only).
@param string $enclosure The field enclosure character (one character only).
@param string $escape The escape character (one character only)
@return string | entailment |
public function quoteString(?string $value): string
{
if ($value===null || $value==='') return 'null';
return "'".$this->mysqli->real_escape_string($value)."'";
} | Returns a literal for a string value that can be safely used in SQL statements.
@param string|null $value The value.
@return string | entailment |
public function searchInRowSet(string $columnName, $value, array $rowSet)
{
if (is_array($rowSet))
{
foreach ($rowSet as $key => $row)
{
if ((string)$row[$columnName]===(string)$value)
{
return $key;
}
}
}
return null;
} | Returns the key of the first row in a row set for which a column has a specific value. Returns null if no row is
found.
@param string $columnName The column name (or in PHP terms the key in an row (i.e. array) in the row set).
@param mixed $value The value to be found.
@param array[] $rowSet The row set.
@return int|string|null
@since 1.0.0
@api | entailment |
protected function multiQuery(string $queries): void
{
if ($this->logQueries)
{
$time0 = microtime(true);
$tmp = $this->mysqli->multi_query($queries);
if ($tmp===false)
{
throw new DataLayerException($this->mysqli->errno, $this->mysqli->error, $queries);
}
$this->queryLog[] = ['query' => $queries, 'time' => microtime(true) - $time0];
}
else
{
$tmp = $this->mysqli->multi_query($queries);
if ($tmp===false)
{
throw new DataLayerException($this->mysqli->errno, $this->mysqli->error, $queries);
}
}
} | Executes multiple SQL statements.
Wrapper around [multi_mysqli::query](http://php.net/manual/mysqli.multi-query.php), however on failure an exception
is thrown.
@param string $queries The SQL statements.
@return void | entailment |
protected function mySqlError(string $method): void
{
$message = 'MySQL Error no: '.$this->mysqli->errno."\n";
$message .= $this->mysqli->error;
$message .= "\n";
$message .= $method;
$message .= "\n";
throw new RuntimeException('%s', $message);
} | Throws an exception with error information provided by MySQL/[mysqli](http://php.net/manual/en/class.mysqli.php).
This method must called after a method of [mysqli](http://php.net/manual/en/class.mysqli.php) returns an
error only.
@param string $method The name of the method that has failed. | entailment |
protected function query(string $query): \mysqli_result
{
if ($this->logQueries)
{
$time0 = microtime(true);
$ret = $this->mysqli->query($query);
if ($ret===false)
{
throw new DataLayerException($this->mysqli->errno, $this->mysqli->error, $query);
}
$this->queryLog[] = ['query' => $query, 'time' => microtime(true) - $time0];
}
else
{
$ret = $this->mysqli->query($query);
if ($ret===false)
{
throw new DataLayerException($this->mysqli->errno, $this->mysqli->error, $query);
}
}
return $ret;
} | Executes a query (i.e. SELECT, SHOW, DESCRIBE or EXPLAIN) with a result set.
Wrapper around [mysqli::query](http://php.net/manual/mysqli.query.php), however on failure an exception is thrown.
For other SQL statements, see @realQuery.
@param string $query The SQL statement.
@return \mysqli_result | entailment |
protected function realQuery(string $query): void
{
if ($this->logQueries)
{
$time0 = microtime(true);
$tmp = $this->mysqli->real_query($query);
if ($tmp===false)
{
throw new DataLayerException($this->mysqli->errno, $this->mysqli->error, $query);
}
$this->queryLog[] = ['query' => $query,
'time' => microtime(true) - $time0];
}
else
{
$tmp = $this->mysqli->real_query($query);
if ($tmp===false)
{
throw new DataLayerException($this->mysqli->errno, $this->mysqli->error, $query);
}
}
} | Execute a query without a result set.
Wrapper around [mysqli::real_query](http://php.net/manual/en/mysqli.real-query.php), however on failure an
exception is thrown.
For SELECT, SHOW, DESCRIBE or EXPLAIN queries, see @query.
@param string $query The SQL statement. | entailment |
protected function sendLongData(mysqli_stmt $statement, int $paramNr, ?string $data): void
{
if ($data!==null)
{
$n = strlen($data);
$p = 0;
while ($p<$n)
{
$b = $statement->send_long_data($paramNr, substr($data, $p, $this->chunkSize));
if (!$b) $this->mySqlError('mysqli_stmt::send_long_data');
$p += $this->chunkSize;
}
}
} | Send data in blocks to the MySQL server.
Wrapper around [mysqli_stmt::send_long_data](http://php.net/manual/mysqli-stmt.send-long-data.php).
@param mysqli_stmt $statement The prepared statement.
@param int $paramNr The 0-indexed parameter number.
@param string|null $data The data. | entailment |
private function executeTableShowFooter(array $columns): void
{
$separator = '+';
foreach ($columns as $column)
{
$separator .= str_repeat('-', $column['length'] + 2).'+';
}
echo $separator, "\n";
} | Helper method for method executeTable. Shows table footer.
@param array $columns | entailment |
private function executeTableShowHeader(array $columns): void
{
$separator = '+';
$header = '|';
foreach ($columns as $column)
{
$separator .= str_repeat('-', $column['length'] + 2).'+';
$spaces = ($column['length'] + 2) - mb_strlen((string)$column['header']);
$spacesLeft = (int)floor($spaces / 2);
$spacesRight = (int)ceil($spaces / 2);
$fillerLeft = ($spacesLeft>0) ? str_repeat(' ', $spacesLeft) : '';
$fillerRight = ($spacesRight>0) ? str_repeat(' ', $spacesRight) : '';
$header .= $fillerLeft.$column['header'].$fillerRight.'|';
}
echo "\n", $separator, "\n";
echo $header, "\n";
echo $separator, "\n";
} | Helper method for method executeTable. Shows table header.
@param array $columns | entailment |
public function render()
{
$output[] = $this->open();
if ($this->hasChildNodes()) {
$output[] = implode(PHP_EOL, $this->childNodes->getArrayCopy());
}
if ($this->hasTextContent()) {
$output[] = implode('', $this->textContent->getArrayCopy());
}
$output[] = $this->close();
return implode(PHP_EOL, $output);
} | Label::render
@return string | entailment |
public function initialize(array $config = [])
{
if (count($config)) {
$this->setConfig($config);
} elseif (false !== ($config = config('view')->presenter)) {
$this->setConfig($config);
}
// autoload presenter assets
if (isset($config[ 'assets' ])) {
$this->assets->autoload($config[ 'assets' ]);
}
// autoload presenter theme
if(isset($config['theme'])) {
$this->setTheme($config['theme']);
}
return $this;
} | Presenter::initialize
@param array $config
@return static | entailment |
public function setTheme($theme)
{
if($this->theme instanceof Theme) {
$this->assets->removeFilePath($this->theme->getRealPath());
}
if (is_bool($theme)) {
$this->theme = false;
} elseif(($moduleTheme = modules()->top()->getTheme($theme, true)) instanceof Theme) {
$this->theme = $moduleTheme;
} elseif(($appTheme = modules()->first()->getTheme($theme, true)) instanceof Theme) {
$this->theme = $appTheme;
}
if($this->theme) {
if ( ! defined('PATH_THEME')) {
define('PATH_THEME', $this->theme->getRealPath());
}
// add theme assets directory
$this->assets->pushFilePath($this->theme->getRealPath());
if(is_dir($themeViewPath = $this->theme->getRealPath() . 'views' . DIRECTORY_SEPARATOR)) {
// add theme view directory
view()->addFilePath($this->theme->getRealPath());
// add theme output directory
output()->pushFilePath($themeViewPath);
$modules = modules()->getArrayCopy();
foreach($modules as $module) {
if ( ! in_array($module->getType(), ['KERNEL', 'FRAMEWORK', 'APP'])) {
$moduleResourcesPath = str_replace(PATH_RESOURCES, '', $module->getResourcesDir());
if(is_dir($themeViewPath . $moduleResourcesPath)) {
view()->pushFilePath($themeViewPath . $moduleResourcesPath);
}
}
}
}
}
return $this;
} | Presenter::setTheme
@param string $theme
@return static | entailment |
public function store($offset, $value, $replace = false)
{
if ($value instanceof \Closure) {
parent::store($offset, call_user_func($value, $this));
} else {
parent::store($offset, $value);
}
} | Presenter::store
@param string $offset
@param mixed $value
@param bool $replace | entailment |
public function getArrayCopy()
{
$storage = $this->storage;
// Add Properties
$storage[ 'meta' ] = $this->meta;
$storage[ 'page' ] = $this->page;
$storage[ 'assets' ] = new SplArrayObject([
'head' => $this->assets->getHead(),
'body' => $this->assets->getBody(),
]);
$storage[ 'partials' ] = $this->partials;
$storage[ 'widgets' ] = $this->widgets;
$storage[ 'theme' ] = $this->theme;
// Add Services
$storage[ 'config' ] = config();
$storage[ 'language' ] = language();
$storage[ 'session' ] = session();
$storage[ 'presenter' ] = presenter();
$storage[ 'input' ] = input();
if (services()->has('csrfProtection')) {
$storage[ 'csrfToken' ] = services()->get('csrfProtection')->getToken();
}
return $storage;
} | Presenter::getArrayCopy
@return array | entailment |
public function get($property)
{
// CodeIgniter property aliasing
if ($property === 'load') {
$property = 'loader';
}
if (services()->has($property)) {
return services()->get($property);
} elseif ($property === 'model') {
return models('controller');
} elseif ($property === 'services' || $property === 'libraries') {
return services();
} elseif (method_exists($this, $property)) {
return call_user_func([&$this, $property]);
}
return parent::get($property);
} | Presenter::get
@param string $property
@return mixed | entailment |
public function createTokenResponse(
ServerRequestInterface $request,
Client $client = null,
TokenOwnerInterface $owner = null
): ResponseInterface {
$postParams = $request->getParsedBody();
$code = $postParams['code'] ?? null;
if (null === $code) {
throw OAuth2Exception::invalidRequest('Could not find the authorization code in the request');
}
/* @var \ZfrOAuth2\Server\Model\AuthorizationCode $authorizationCode */
$authorizationCode = $this->authorizationCodeService->getToken($code);
if (null === $authorizationCode || $authorizationCode->isExpired()) {
throw OAuth2Exception::invalidGrant('Authorization code cannot be found or is expired');
}
$clientId = $postParams['client_id'] ?? null;
if ($authorizationCode->getClient()->getId() !== $clientId) {
throw OAuth2Exception::invalidRequest(
'Authorization code\'s client does not match with the one that created the authorization code'
);
}
// If owner is null, we reuse the same as the authorization code
$owner = $owner ?: $authorizationCode->getOwner();
// Everything is okey, let's start the token generation!
$scopes = $authorizationCode->getScopes(); // reuse the scopes from the authorization code
$accessToken = $this->accessTokenService->createToken($owner, $client, $scopes);
// Before generating a refresh token, we must make sure the authorization server supports this grant
$refreshToken = null;
if ($this->authorizationServer->hasGrant(RefreshTokenGrant::GRANT_TYPE)) {
$refreshToken = $this->refreshTokenService->createToken($owner, $client, $scopes);
}
return $this->prepareTokenResponse($accessToken, $refreshToken);
} | {@inheritdoc}
@throws OAuth2Exception | entailment |
public function setMedia($src)
{
$src = str_replace(
[
'youtube.com/',
'youtu.be',
'?rel=0',
],
[
'youtube.com/embed/',
'youtube.com/embed/',
'',
],
$src
);
if (strpos($src, 'youtube') !== false) {
$src .= '?rel=0';
}
$this->media->attributes->addAttribute('src', $src);
return $this;
} | Embed::setMedia
@param string $src
@return static | entailment |
public function render()
{
$output[] = $this->open();
$output[] = $this->media;
$output[] = $this->close();
return implode(PHP_EOL, $output);
} | Embed::render
@return string | entailment |
public function createButtonGroup()
{
$node = new Group();
$this->childNodes->push($node);
return $this->childNodes->last();
} | Toolbar::createButtonGroup
@return Group | entailment |
public function createDropdownButtonGroup($label)
{
if ($label instanceof Dropdown) {
$node = clone $label;
} else {
$node = new Dropdown($label);
}
$this->childNodes->push($node);
return $this->childNodes->last();
} | Toolbar::createDropdownButtonGroup
@param string|Dropdown $label
@return Dropdown | entailment |
public function createInputGroup()
{
$node = new \O2System\Framework\Libraries\Ui\Components\Form\Input\Group();
$this->childNodes->push($node);
return $this->childNodes->last();
} | Toolbar::createInputGroup
@return \O2System\Framework\Libraries\Ui\Components\Form\Input\Group | entailment |
public static function staticToStatic(string $sourceName, string $targetName): void
{
$source = file_get_contents($sourceName);
$sourceClass = basename($sourceName, '.php');
$targetClass = basename($targetName, '.php');
$source = NonStatic::nonStatic($source, $sourceClass, $targetClass);
file_put_contents($targetName, $source);
} | Makes non static implementation of a static class.
@param string $sourceName The filename with the static class.
@param string $targetName The filename where the non static class must be written. | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->io = new StratumStyle($input, $output);
$sourceFilename = $input->getArgument('source');
$targetFilename = dirname($sourceFilename).'/'.basename($input->getArgument('target'));
if (basename($sourceFilename)===basename($targetFilename))
{
throw new RuntimeException('Source and target files is the same file');
}
self::staticToStatic($sourceFilename, $targetFilename);
return 0;
} | Executes the actual PhpStratum program. Returns 0 is everything went fine. Otherwise, returns non-zero.
@param InputInterface $input An InputInterface instance
@param OutputInterface $output An OutputInterface instance
@return int | entailment |
protected function mappingCurrentModel($currentModel)
{
if ($currentModel instanceof Model) {
$this->currentModel = $currentModel;
$this->currentTable = $this->currentModel->table;
$this->currentPrimaryKey = $this->currentModel->primaryKey;
} elseif (class_exists($currentModel)) {
$this->currentModel = models($currentModel);
$this->currentTable = $this->currentModel->table;
$this->currentPrimaryKey = $this->currentModel->primaryKey;
} else {
$this->currentTable = $currentModel;
$this->currentPrimaryKey = 'id';
}
} | AbstractMap::mappingCurrentModel
@param string|Model $currentModel | entailment |
protected function mappingReferenceModel($referenceModel)
{
if ($referenceModel instanceof Model) {
$this->referenceModel = $referenceModel;
$this->referenceTable = $this->referenceModel->table;
$this->referencePrimaryKey = $this->referenceModel->primaryKey;
} elseif (class_exists($referenceModel)) {
$this->referenceModel = models($referenceModel);
$this->referenceTable = $this->referenceModel->table;
$this->referencePrimaryKey = $this->referenceModel->primaryKey;
} else {
$this->referenceModel = new class extends Model
{
};
$this->referenceModel->table = $this->referenceTable = $referenceModel;
$this->referenceModel->primaryKey = $this->referencePrimaryKey = 'id';
}
if (empty($this->currentForeignKey)) {
$this->currentForeignKey = $this->referencePrimaryKey . '_' . str_replace([
't_',
'tm_',
'tr_',
'tb_',
], '', $this->referenceTable);
}
} | AbstractMap::mappingReferenceModel
@param string|Model $referenceModel | entailment |
protected function belongsTo($referenceModel, $foreignKey = null)
{
return (new Relations\BelongsTo(
new Relations\Maps\Inverse($this, $referenceModel, $foreignKey)
))->getResult();
} | RelationTrait::belongsTo
Belongs To is the inverse of one to one relationship.
@param string|Model $referenceModel
@param string|null $foreignKey
@return Row|bool | entailment |
protected function belongsToThrough(
$referenceModel,
$intermediaryModel,
$intermediaryCurrentForeignKey = null,
$intermediaryReferenceForeignKey = null
) {
return (new Relations\BelongsToThrough(
new Relations\Maps\Intermediary($this, $referenceModel, $intermediaryModel, $intermediaryCurrentForeignKey,
$intermediaryReferenceForeignKey)
))->getResult();
} | RelationTrait::belongsToThrough
@param string|Model $referenceModel
@param string|Model $intermediaryModel
@param string|null $intermediaryCurrentForeignKey
@param string|null $intermediaryReferenceForeignKey
@return array|bool|\O2System\Framework\Models\Sql\DataObjects\Result\Row | entailment |
protected function belongsToMany($referenceModel, $foreignKey = null)
{
return (new Relations\BelongsToMany(
new Relations\Maps\Inverse($this, $referenceModel, $foreignKey)
))->getResult();
} | RelationTrait::belongsToMany
Belongs To is the inverse of one to many relationship.
@param string|Model $referenceModel String of table name or AbstractModel
@param string|null $foreignKey
@return Row|bool | entailment |
protected function belongsToManyThrough(
$referenceModel,
$intermediaryModel,
$intermediaryCurrentForeignKey = null,
$intermediaryReferenceForeignKey = null
) {
return (new Relations\BelongsToManyThrough(
new Relations\Maps\Intermediary($this, $referenceModel, $intermediaryModel, $intermediaryCurrentForeignKey,
$intermediaryReferenceForeignKey)
))->getResult();
} | RelationTrait::belongsToManyThrough
@param string|Model $referenceModel
@param string|Model $intermediaryModel
@param string|null $intermediaryCurrentForeignKey
@param string|null $intermediaryReferenceForeignKey
@return array|bool|\O2System\Framework\Models\Sql\DataObjects\Result\Row | entailment |
protected function hasOne($referenceModel, $foreignKey = null)
{
return (new Relations\HasOne(
new Relations\Maps\Reference($this, $referenceModel, $foreignKey)
))->getResult();
} | RelationTrait::hasOne
Has one is a one to one relationship. The reference model might be associated
with one relation model / table.
@param string|Model $referenceModel String of table name or AbstractModel
@param string|null $foreignKey
@return Row|bool | entailment |
Subsets and Splits