sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function initServiceClient()
{
if ($this->httpClient === null) {
$this->initHttpClients();
}
$serviceDescription = new Description($this->config->getServiceDescriptionConfig());
$serviceClient = new GuzzleClient($this->getHttpClient(), $serviceDescription);
foreach ($this->config->getClientDefaultsConfig() as $option => $value) {
$serviceClient->setConfig($option, $value);
}
$this->description = $serviceDescription;
$this->serviceClient = $serviceClient;
}
|
Sets the http client
|
entailment
|
public function initHttpClients()
{
$clientConfig = $this->config->getHttpClientConfig();
$authClient = new HttpClient($clientConfig);
$this->setAuthHttpClient($authClient);
$clientConfig['handler'] = $this->initHandlerStack();
$client = new HttpClient($clientConfig);
$this->setHttpClient($client);
}
|
Sets the http client
|
entailment
|
public function setParent(Category $parent = null): Category
{
if ($parent === $this) {
// Refuse the category to have itself as parent.
$this->parent = null;
return $this;
}
$this->parent = $parent;
// Ensure bidirectional relation is respected.
if ($parent && false === $parent->getChildren()->indexOf($this)) {
$parent->addChild($this);
}
return $this;
}
|
@param Category|null $parent
@return Category
|
entailment
|
public function addChild(Category $category): Category
{
$this->children->add($category);
if ($category->getParent() !== $this) {
$category->setParent($this);
}
return $this;
}
|
@param Category $category
@return Category
|
entailment
|
public function addPage(Page $page): Category
{
$this->children->add($page);
if ($page->getCategory() !== $this) {
$page->setCategory($this);
}
return $this;
}
|
@param Page $page
@return Category
|
entailment
|
public function removePage(Page $page): Category
{
$this->children->removeElement($page);
$page->setCategory(null);
return $this;
}
|
@param Page $page
@return Category
|
entailment
|
public function onRemove(LifecycleEventArgs $event)
{
$em = $event->getEntityManager();
if (count($this->children)) {
foreach ($this->children as $child) {
$child->setParent(null);
$em->persist($child);
}
}
$this->enabled = false;
$this->parent = null;
$this->name .= '-'.$this->getId().'-deleted';
$this->slug .= '-'.$this->getId().'-deleted';
}
|
@ORM\PreRemove()
@param LifecycleEventArgs $event
|
entailment
|
public function parse($token)
{
$parts = explode('.', $token);
if (count($parts) !== 3) {
throw new InvalidArgumentException('Token is invalid');
}
$this->token = $token;
$this->header = json_decode(base64_decode($parts[0]), true);
$this->payload = json_decode(base64_decode($parts[1]), true);
$this->signature = $parts[2];
}
|
Parse a Token
@param string $token
@throws InvalidArgumentException
|
entailment
|
public function isValid()
{
$payload = $this->getPayload();
if (!isset($payload['exp'])) {
return false;
}
$expireDateTime = DateTimeImmutable::createFromFormat('U', $payload['exp']);
$now = new DateTime('now');
return ($expireDateTime->getTimestamp() - $now->getTimestamp()) > 0;
}
|
Checks if the token is valid
@return bool
|
entailment
|
public function findByCategory(Category $category, $order, $orderBy, $page, $limit): Paginator
{
$qb = $this->createQueryBuilder('page')
->where('page.category = :category')
->andWhere('page.enabled = :enabled')
->orderBy('page.'.$orderBy, $order)
->setMaxResults($limit)
->setFirstResult($limit * ($page-1))
->setParameter('category', $category)
->setParameter('enabled', true)
;
return new Paginator($qb->getQuery()->useResultCache($this->cacheEnabled, $this->cacheTtl));
}
|
@param Category $category
@param string $order
@param string $orderBy
@param int $page
@param int $limit
@return Paginator
|
entailment
|
public function findFrontPages(array $slugs = [], $host = null, $locale = null)
{
$qb = $this->createQueryBuilder('page')
->where('page.enabled = :enabled')
->leftJoin('page.category', 'category')
->andWhere('page.category is null OR category.enabled = :enabled')
->setParameter('enabled', true)
;
// Will search differently if we're looking for homepage.
$searchForHomepage = 0 === count($slugs);
if (true === $searchForHomepage) {
// If we are looking for homepage, let's get only the first one.
$qb
->andWhere('page.homepage = :homepage')
->setParameter('homepage', true)
->setMaxResults(1)
;
} elseif (1 === count($slugs)) {
$qb
->andWhere('page.slug = :slug')
->setParameter('slug', reset($slugs))
->setMaxResults(1)
;
} else {
$qb
->andWhere('page.slug IN ( :slugs )')
->setParameter('slugs', $slugs)
;
}
$hostWhere = 'page.host IS NULL';
if (null !== $host) {
$hostWhere .= ' OR page.host = :host';
$qb->setParameter('host', $host);
$qb->addOrderBy('page.host', 'asc');
}
$qb->andWhere($hostWhere);
$localeWhere = 'page.locale IS NULL';
if (null !== $locale) {
$localeWhere .= ' OR page.locale = :locale';
$qb->setParameter('locale', $locale);
$qb->addOrderBy('page.locale', 'asc');
}
$qb->andWhere($localeWhere);
// Then the last page will automatically be one that has both properties.
$qb
->orderBy('page.host', 'asc')
->addOrderBy('page.locale', 'asc')
;
/** @var Page[] $results */
$results = $qb->getQuery()
->useResultCache($this->cacheEnabled, $this->cacheTtl)
->getResult()
;
if (0 === count($results)) {
return $results;
}
// If we're looking for a homepage, only get the first result (matching more properties).
if (true === $searchForHomepage && count($results) > 0) {
reset($results);
$results = [$results[0]];
}
$resultsSortedBySlug = [];
foreach ($results as $page) {
$resultsSortedBySlug[$page->getSlug()] = $page;
}
$pages = $resultsSortedBySlug;
if (count($slugs) > 0) {
$pages = [];
foreach ($slugs as $value) {
if (!array_key_exists($value, $resultsSortedBySlug)) {
// Means at least one page in the tree is not enabled
return [];
}
$pages[$value] = $resultsSortedBySlug[$value];
}
}
return $pages;
}
|
Will search for pages to show in front depending on the arguments.
If slugs are defined, there's no problem in looking for nulled host or locale,
because slugs are unique, so it does not.
@param array $slugs
@param string|null $host
@param string|null $locale
@return Page[]
|
entailment
|
protected function getFinalTreeElement(array $slugs, array $elements)
{
// Will check that slugs and elements match
$slugsElements = array_keys($elements);
$sortedSlugs = $slugs;
sort($sortedSlugs);
sort($slugsElements);
if ($sortedSlugs !== $slugsElements || !count($slugs) || count($slugs) !== count($elements)) {
throw $this->createNotFoundException();
}
/** @var Page|Category $element */
$element = null;
/** @var Page|Category $previousElement */
$previousElement = null;
foreach ($slugs as $slug) {
$element = $elements[$slug] ?? null;
$match = false;
if ($element) {
// Only for the first iteration
$match = $previousElement
? $element->getParent() && $previousElement->getSlug() === $element->getParent()->getSlug()
: true;
$previousElement = $element;
}
if (!$match) {
throw $this->createNotFoundException((new \ReflectionClass($element))->getShortName().' hierarchy not found.');
}
}
return $element;
}
|
Slugs HAVE TO be ordered exactly as in the request.
This method will check that, in $elements, we have the same keys as in $slugs,
and that the hierarchy is correct.
This also prevents things like /children/parent to work,
as it should be /parent/children.
@param array $slugs
@param Page[]|Category[] $elements
@return Category|Page
|
entailment
|
public function make(array $config): Client
{
$config = $this->getConfig($config);
return $this->getClient($config);
}
|
Make a new gitlab client.
@param array $config
@return \Gitlab\Client
|
entailment
|
protected function getClient(array $config): Client
{
$client = Client::create($config['url']);
$client->authenticate(
$config['token'],
array_get($config, 'method', Client::AUTH_URL_TOKEN),
array_get($config, 'sudo', null)
);
return $client;
}
|
Get the main client.
@param array $config
@return \Gitlab\Client
|
entailment
|
public function findFrontCategories(array $slugs)
{
$qb = $this->createQueryBuilder('category')
->where('category.enabled = :enabled')
->setParameter('enabled', true)
->andWhere('category.slug IN ( :slugs )')
->setParameter('slugs', $slugs)
;
/** @var Category[] $results */
$results = $qb
->getQuery()
->useResultCache($this->cacheEnabled, $this->cacheTtl)
->getResult()
;
$resultsSortedBySlug = [];
foreach ($results as $category) {
$resultsSortedBySlug[$category->getSlug()] = $category;
}
return $resultsSortedBySlug;
}
|
@param array $slugs
@return Category[]
|
entailment
|
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('orbitale_cms');
$rootNode
->addDefaultsIfNotSet()
->children()
->scalarNode('page_class')
->isRequired()
->validate()
->ifString()
->then(function($value) {
if (!class_exists($value) || !is_a($value, Page::class, true)) {
throw new InvalidConfigurationException(sprintf(
'Page class must be a valid class extending %s. "%s" given.',
Page::class, $value
));
}
return $value;
})
->end()
->end()
->scalarNode('category_class')
->isRequired()
->validate()
->ifString()
->then(function($value) {
if (!class_exists($value) || !is_a($value, Category::class, true)) {
throw new InvalidConfigurationException(sprintf(
'Category class must be a valid class extending %s. "%s" given.',
Category::class, $value
));
}
return $value;
})
->end()
->end()
->arrayNode('layouts')
->defaultValue([
'front' => [
'resource' => '@OrbitaleCms/default_layout.html.twig',
'pattern' => '',
],
])
->useAttributeAsKey('name')
->prototype('array')
->addDefaultsIfNotSet()
->children()
->scalarNode('name')->end()
->scalarNode('resource')->isRequired()->end()
->arrayNode('assets_css')->prototype('scalar')->end()->end()
->arrayNode('assets_js')->prototype('scalar')->end()->end()
->scalarNode('pattern')->defaultValue('')->end()
->scalarNode('host')->defaultValue('')->end()
->end()
->end()
->end()
->arrayNode('design')
->addDefaultsIfNotSet()
->children()
->scalarNode('breadcrumbs_class')->defaultValue('breadcrumb')->end()
->scalarNode('breadcrumbs_link_class')->defaultValue('')->end()
->scalarNode('breadcrumbs_current_class')->defaultValue('')->end()
->scalarNode('breadcrumbs_separator')->defaultValue('>')->end()
->scalarNode('breadcrumbs_separator_class')->defaultValue('breadcrumb-separator')->end()
->end()
->end()
->arrayNode('cache')
->addDefaultsIfNotSet()
->children()
->booleanNode('enabled')->defaultFalse()->end()
->integerNode('ttl')->defaultValue(300)->end()
->end()
->end()
->end();
return $treeBuilder;
}
|
{@inheritdoc}
|
entailment
|
public function indexAction(Request $request, string $slugs = '', string $_locale = null): Response
{
if (preg_match('~/$~', $slugs)) {
return $this->redirect($this->generateUrl('orbitale_cms_page', ['slugs' => rtrim($slugs, '/')]));
}
$this->request = $request;
$this->request->setLocale($_locale ?: $this->request->getLocale());
$slugsArray = preg_split('~/~', $slugs, -1, PREG_SPLIT_NO_EMPTY);
$pages = $this->getPages($slugsArray);
$currentPage = $this->getCurrentPage($pages, $slugsArray);
// If we have slugs and the current page is homepage,
// we redirect to homepage for "better" url and SEO management.
// Example: if "/home" is a homepage, "/home" url is redirected to "/".
if ($slugs && $currentPage->isHomepage()) {
$params = ['slugs' => ''];
if ($currentPage->getLocale()) {
// Force locale if the Page has one
$params['_locale'] = $currentPage->getLocale();
}
return $this->redirect($this->generateUrl('orbitale_cms_page', $params));
}
return $this->render('@OrbitaleCms/Front/index.html.twig', [
'pages' => $pages,
'page' => $currentPage,
]);
}
|
@param Request $request
@param string $slugs
@param string|null $_locale
@return Response
|
entailment
|
protected function getPages(array $slugsArray = [])
{
/** @var Page[] $pages */
$pages = $this->get('orbitale_cms.page_repository')
->findFrontPages($slugsArray, $this->request->getHost(), $this->request->getLocale())
;
if (!count($pages) || (count($slugsArray) && count($pages) !== count($slugsArray))) {
throw $this->createNotFoundException(count($slugsArray)
? 'Page not found'
: 'No homepage has been configured. Please check your existing pages or create a homepage in your application.');
}
return $pages;
}
|
Retrieves the page list based on slugs.
Also checks the hierarchy of the different pages.
@param array $slugsArray
@return Page[]
|
entailment
|
protected function getCurrentPage(array $pages, array $slugsArray): Page
{
if (count($pages) === count($slugsArray)) {
$currentPage = $this->getFinalTreeElement($slugsArray, $pages);
} else {
$currentPage = current($pages);
}
return $currentPage;
}
|
Retrieves the current page based on page list and entered slugs.
@param Page[] $pages
@param array $slugsArray
@return Page
|
entailment
|
public function fetch($id)
{
if (!file_exists($this->filename($id))) {
return false;
}
$filedata = file_get_contents($this->filename($id));
$data = json_decode($filedata, true);
if ($data['ttl'] !== null) {
if (($data['time'] + $data['ttl']) < time()) {
return false;
}
}
return $data['data'];
}
|
Fetches an entry from the cache or returns false if not exists.
@param string $id
@return string|false
|
entailment
|
public function save($id, $data, $ttl = null)
{
$filedata = [
'time' => time(),
'ttl' => $ttl,
'data' => $data,
];
return false !== file_put_contents($this->filename($id), json_encode($filedata), LOCK_EX);
}
|
Puts data into the cache.
@param string $id
@param string $data
@param int $ttl
@return bool
|
entailment
|
private function createWritablePathIfNotExists($path)
{
if (!is_dir($path)) {
// check if parentdir exists, and create this first.
$parentdir = dirname($path);
if (!is_dir($parentdir)) {
$this->createWritablePathIfNotExists($parentdir);
}
if (!is_writable($parentdir)) {
throw new \InvalidArgumentException(sprintf(
'The parent directory "%s" is not writable.',
$parentdir
));
}
if (!mkdir($path, $this->dirMode)) {
return false;
}
}
if (!is_writable($path)) {
throw new \InvalidArgumentException(sprintf(
'The path "%s" is not writable.',
$path
));
}
return true;
}
|
Create path if needed.
@param string $path
@return bool
|
entailment
|
public function append(Response $xResponse)
{
if(!$this->xResponse)
{
$this->xResponse = $xResponse;
}
elseif(get_class($this->xResponse) == get_class($xResponse))
{
if($this->xResponse != $xResponse)
{
$this->xResponse->appendResponse($xResponse);
}
}
else
{
$this->debug($this->trans('errors.mismatch.types', array('class' => get_class($xResponse))));
}
}
|
Append one response object onto the end of another
You cannot append a given response onto the end of a response of different type.
If no prior response has been appended, this response becomes the main response
object to which other response objects will be appended.
@param Response $xResponse The response object to be appended
@return void
|
entailment
|
public function printDebug()
{
if(($this->xResponse))
{
foreach($this->aDebugMessages as $sMessage)
{
$this->xResponse->debug($sMessage);
}
$this->aDebugMessages = [];
}
}
|
Prints the debug messages into the current response object
@return void
|
entailment
|
public function getValue($row): string
{
$escape = $this->get('escape', false);
$value = $this->attributes['value']($row);
if ($value instanceof Renderable) {
return $value->render();
}
return $escape === true ? e($value) : $value;
}
|
Get value of column.
@param mixed $row
@return string
|
entailment
|
private function getClassOptions($sClassName, array $aDirectoryOptions, array $aDefaultOptions = [])
{
$aOptions = $aDefaultOptions;
if(key_exists('separator', $aDirectoryOptions))
{
$aOptions['separator'] = $aDirectoryOptions['separator'];
}
if(key_exists('protected', $aDirectoryOptions))
{
$aOptions['protected'] = $aDirectoryOptions['protected'];
}
if(key_exists('*', $aDirectoryOptions))
{
$aOptions = array_merge($aOptions, $aDirectoryOptions['*']);
}
if(key_exists($sClassName, $aDirectoryOptions))
{
$aOptions = array_merge($aOptions, $aDirectoryOptions[$sClassName]);
}
return $aOptions;
}
|
Get a given class options from specified directory options
@param string $sClassName The name of the class
@param array $aDirectoryOptions The directory options
@param array $aDefaultOptions The default options
@return array
|
entailment
|
private function getOptionsFromClass($sClassName)
{
if(!key_exists($sClassName, $this->aClassOptions))
{
return null; // Class not registered
}
return $this->aClassOptions[$sClassName];
}
|
Find a class name is register with Jaxon::CALLABLE_CLASS type
@param string $sClassName The class name of the callable object
@return array|null
|
entailment
|
private function getOptionsFromNamespace($sClassName, $sNamespace = null)
{
// Find the corresponding namespace
if($sNamespace === null)
{
foreach(array_keys($this->aNamespaceOptions) as $_sNamespace)
{
if(substr($sClassName, 0, strlen($_sNamespace) + 1) == $_sNamespace . '\\')
{
$sNamespace = $_sNamespace;
break;
}
}
}
if($sNamespace === null)
{
return null; // Class not registered
}
// Get the class options
$aOptions = $this->aNamespaceOptions[$sNamespace];
$aDefaultOptions = []; // ['namespace' => $aOptions['namespace']];
if(key_exists('separator', $aOptions))
{
$aDefaultOptions['separator'] = $aOptions['separator'];
}
return $this->getClassOptions($sClassName, $aOptions, $aDefaultOptions);
}
|
Find a class name is register with Jaxon::CALLABLE_DIR type
@param string $sClassName The class name of the callable object
@param string|null $sNamespace The namespace
@return array|null
|
entailment
|
protected function _getCallableObject($sClassName, array $aOptions)
{
// Make sure the registered class exists
if(key_exists('include', $aOptions))
{
require_once($aOptions['include']);
}
if(!class_exists($sClassName))
{
return null;
}
// Create the callable object
$xCallableObject = new \Jaxon\Request\Support\CallableObject($sClassName);
$this->aCallableOptions[$sClassName] = [];
foreach($aOptions as $sName => $xValue)
{
if($sName == 'separator' || $sName == 'protected')
{
$xCallableObject->configure($sName, $xValue);
}
elseif(is_array($xValue) && $sName != 'include')
{
// These options are to be included in javascript code.
$this->aCallableOptions[$sClassName][$sName] = $xValue;
}
}
$this->aCallableObjects[$sClassName] = $xCallableObject;
// Register the request factory for this callable object
jaxon()->di()->set($sClassName . '_Factory_Rq', function () use ($sClassName) {
$xCallableObject = $this->aCallableObjects[$sClassName];
return new \Jaxon\Factory\Request\Portable($xCallableObject);
});
// Register the paginator factory for this callable object
jaxon()->di()->set($sClassName . '_Factory_Pg', function () use ($sClassName) {
$xCallableObject = $this->aCallableObjects[$sClassName];
return new \Jaxon\Factory\Request\Paginator($xCallableObject);
});
return $xCallableObject;
}
|
Find a callable object by class name
@param string $sClassName The class name of the callable object
@param array $aOptions The callable object options
@return object
|
entailment
|
public function getCallableObject($sClassName)
{
// Replace all separators ('.' and '_') with antislashes, and remove the antislashes
// at the beginning and the end of the class name.
$sClassName = trim(str_replace(['.', '_'], ['\\', '\\'], (string)$sClassName), '\\');
if(key_exists($sClassName, $this->aCallableObjects))
{
return $this->aCallableObjects[$sClassName];
}
$aOptions = $this->getOptionsFromClass($sClassName);
if($aOptions === null)
{
$aOptions = $this->getOptionsFromNamespace($sClassName);
}
if($aOptions === null)
{
return null;
}
return $this->_getCallableObject($sClassName, $aOptions);
}
|
Find a callable object by class name
@param string $sClassName The class name of the callable object
@return object
|
entailment
|
private function createCallableObjects()
{
// Create callable objects for registered classes
foreach($this->aClassOptions as $sClassName => $aClassOptions)
{
if(!key_exists($sClassName, $this->aCallableObjects))
{
$this->_getCallableObject($sClassName, $aClassOptions);
}
}
// Create callable objects for registered namespaces
$sDS = DIRECTORY_SEPARATOR;
foreach($this->aNamespaceOptions as $sNamespace => $aOptions)
{
if(key_exists($sNamespace, $this->aNamespaces))
{
continue;
}
$this->aNamespaces[$sNamespace] = $sNamespace;
// Iterate on dir content
$sDirectory = $aOptions['directory'];
$itDir = new RecursiveDirectoryIterator($sDirectory);
$itFile = new RecursiveIteratorIterator($itDir);
foreach($itFile as $xFile)
{
// skip everything except PHP files
if(!$xFile->isFile() || $xFile->getExtension() != 'php')
{
continue;
}
// Find the class path (the same as the class namespace)
$sClassPath = $sNamespace;
$sRelativePath = substr($xFile->getPath(), strlen($sDirectory));
$sRelativePath = trim(str_replace($sDS, '\\', $sRelativePath), '\\');
if($sRelativePath != '')
{
$sClassPath .= '\\' . $sRelativePath;
}
$this->aNamespaces[$sClassPath] = ['separator' => $aOptions['separator']];
$sClassName = $sClassPath . '\\' . $xFile->getBasename('.php');
if(!key_exists($sClassName, $this->aCallableObjects))
{
$aClassOptions = $this->getOptionsFromNamespace($sClassName, $sNamespace);
if($aClassOptions !== null)
{
$this->_getCallableObject($sClassName, $aClassOptions);
}
}
}
}
}
|
Create callable objects for all registered namespaces
@return void
|
entailment
|
protected function getRegisteredObject($sClassName)
{
// Get the corresponding callable object
$xCallableObject = $this->getCallableObject($sClassName);
return ($xCallableObject) ? $xCallableObject->getRegisteredObject() : null;
}
|
Find a user registered callable object by class name
@param string $sClassName The class name of the callable object
@return object
|
entailment
|
public function generateHash()
{
$this->createCallableObjects();
$sHash = '';
foreach($this->aNamespaces as $sNamespace => $aOptions)
{
$sHash .= $sNamespace . $aOptions['separator'];
}
foreach($this->aCallableObjects as $sClassName => $xCallableObject)
{
$sHash .= $sClassName . implode('|', $xCallableObject->getMethods());
}
return md5($sHash);
}
|
Generate a hash for the registered callable objects
@return string
|
entailment
|
public function getScript()
{
$this->createCallableObjects();
$sPrefix = $this->getOption('core.prefix.class');
$aJsClasses = [];
$sCode = '';
foreach(array_keys($this->aNamespaces) as $sNamespace)
{
$offset = 0;
$sJsNamespace = str_replace('\\', '.', $sNamespace);
$sJsNamespace .= '.Null'; // This is a sentinel. The last token is not processed in the while loop.
while(($dotPosition = strpos($sJsNamespace, '.', $offset)) !== false)
{
$sJsClass = substr($sJsNamespace, 0, $dotPosition);
// Generate code for this object
if(!key_exists($sJsClass, $aJsClasses))
{
$sCode .= "$sPrefix$sJsClass = {};\n";
$aJsClasses[$sJsClass] = $sJsClass;
}
$offset = $dotPosition + 1;
}
}
foreach($this->aCallableObjects as $sClassName => $xCallableObject)
{
$aConfig = $this->aCallableOptions[$sClassName];
$aCommonConfig = key_exists('*', $aConfig) ? $aConfig['*'] : [];
$aMethods = [];
foreach($xCallableObject->getMethods() as $sMethodName)
{
// Specific options for this method
$aMethodConfig = key_exists($sMethodName, $aConfig) ?
array_merge($aCommonConfig, $aConfig[$sMethodName]) : $aCommonConfig;
$aMethods[] = [
'name' => $sMethodName,
'config' => $aMethodConfig,
];
}
$sCode .= $this->render('jaxon::support/object.js', [
'sPrefix' => $sPrefix,
'sClass' => $xCallableObject->getJsName(),
'aMethods' => $aMethods,
]);
}
return $sCode;
}
|
Generate client side javascript code for the registered callable objects
@return string
|
entailment
|
private function _setOptions(array $aOptions, $sPrefix = '', $nDepth = 0)
{
$sPrefix = trim((string)$sPrefix);
$nDepth = intval($nDepth);
// Check the max depth
if($nDepth < 0 || $nDepth > 9)
{
throw new \Jaxon\Config\Exception\Data(jaxon_trans('config.errors.data.depth',
array('key' => $sPrefix, 'depth' => $nDepth)));
}
foreach($aOptions as $sName => $xOption)
{
if(is_int($sName))
{
continue;
}
$sName = trim($sName);
$sFullName = ($sPrefix) ? $sPrefix . '.' . $sName : $sName;
// Save the value of this option
$this->aOptions[$sFullName] = $xOption;
// Save the values of its sub-options
if(is_array($xOption))
{
// Recursively read the options in the array
$this->_setOptions($xOption, $sFullName, $nDepth + 1);
}
}
}
|
Recursively set Jaxon options from a data array
@param array $aOptions The options array
@param string $sPrefix The prefix for option names
@param integer $nDepth The depth from the first call
@return void
|
entailment
|
public function setOptions(array $aOptions, $sKeys = '')
{
// Find the config array in the input data
$aKeys = explode('.', (string)$sKeys);
foreach ($aKeys as $sKey)
{
if(($sKey))
{
if(!array_key_exists($sKey, $aOptions) || !is_array($aOptions[$sKey]))
{
return;
}
$aOptions = $aOptions[$sKey];
}
}
$this->_setOptions($aOptions);
}
|
Set the values of an array of config options
@param array $aOptions The options array
@param string $sKeys The keys of the options in the array
@return void
|
entailment
|
public function getOption($sName, $xDefault = null)
{
return (array_key_exists($sName, $this->aOptions) ? $this->aOptions[$sName] : $xDefault);
}
|
Get the value of a config option
@param string $sName The option name
@param mixed $xDefault The default value, to be returned if the option is not defined
@return mixed The option value, or its default value
|
entailment
|
public function getOptionNames($sPrefix)
{
$sPrefix = trim((string)$sPrefix);
$sPrefix = rtrim($sPrefix, '.') . '.';
$sPrefixLen = strlen($sPrefix);
$aOptions = [];
foreach($this->aOptions as $sName => $xValue)
{
if(substr($sName, 0, $sPrefixLen) == $sPrefix)
{
$iNextDotPos = strpos($sName, '.', $sPrefixLen);
$sOptionName = $iNextDotPos === false ? substr($sName, $sPrefixLen) :
substr($sName, $sPrefixLen, $iNextDotPos - $sPrefixLen);
$aOptions[$sOptionName] = $sPrefix . $sOptionName;
}
}
return $aOptions;
}
|
Get the names of the options matching a given prefix
@param string $sPrefix The prefix to match
@return array The options matching the prefix
|
entailment
|
public function setClassName($sClass)
{
$this->sPrefix = $this->getOption('core.prefix.function');
$sClass = trim($sClass, '.\\ ');
if(!$sClass)
{
return $this;
}
if(!($xCallable = $this->xRepository->getCallableObject($sClass)))
{
// Todo: decide which of these values to return
// return null;
return $this;
}
$this->sPrefix = $this->getOption('core.prefix.class') . $xCallable->getJsName() . '.';
return $this;
}
|
Set the name of the class to call
@param string|null $sClass The callable class
@return Factory
|
entailment
|
public function setCallable(CallableObject $xCallable)
{
$this->sPrefix = $this->getOption('core.prefix.class') . $xCallable->getJsName() . '.';
return $this;
}
|
Set the callable object to call
@param CallableObject $xCallable The callable object
@return Factory
|
entailment
|
public function call($sFunction)
{
$aArguments = func_get_args();
$sFunction = (string)$sFunction;
// Remove the function name from the arguments array.
array_shift($aArguments);
// Makes legacy code works
if(strpos($sFunction, '.') !== false)
{
// If there is a dot in the name, then it is a call to a class
$this->sPrefix = $this->getOption('core.prefix.class');
}
// Make the request
$xRequest = new Request($this->sPrefix . $sFunction);
$xRequest->useSingleQuote();
$xRequest->addParameters($aArguments);
return $xRequest;
}
|
Return the javascript call to a Jaxon function or object method
@param string $sFunction The function or method (without class) name
@param ... $xParams The parameters of the function or method
@return Request
|
entailment
|
public function func($sFunction)
{
$aArguments = func_get_args();
$sFunction = (string)$sFunction;
// Remove the function name from the arguments array.
array_shift($aArguments);
// Make the request
$xRequest = new Request($sFunction);
$xRequest->useSingleQuote();
$xRequest->addParameters($aArguments);
return $xRequest;
}
|
Return the javascript call to a generic function
@param string $sFunction The function or method (with class) name
@param ... $xParams The parameters of the function or method
@return Request
|
entailment
|
public function paginate($nItemsTotal, $nItemsPerPage, $nCurrentPage)
{
// Get the args list starting from the $sMethod
$aArgs = array_slice(func_get_args(), 3);
// Make the request
$request = call_user_func_array([$this, 'call'], $aArgs);
$paginator = jaxon()->paginator($nItemsTotal, $nItemsPerPage, $nCurrentPage, $request);
return $paginator->toHtml();
}
|
Make the pagination links for a registered Jaxon class method
@param integer $nItemsTotal The total number of items
@param integer $nItemsPerPage The number of items per page page
@param integer $nCurrentPage The current page
@return string the pagination links
|
entailment
|
public function addNamespace($sNamespace, $sDirectory, $sExtension = '')
{
// The 'jaxon' key cannot be overriden
if($sNamespace == 'jaxon')
{
return;
}
// Save the namespace
$this->aNamespaces[$sNamespace] = [
'directory' => rtrim(trim($sDirectory), "/\\") . DIRECTORY_SEPARATOR,
'extension' => $sExtension,
];
}
|
Add a namespace to the template system
@param string $sNamespace The namespace name
@param string $sDirectory The namespace directory
@param string $sExtension The extension to append to template names
@return void
|
entailment
|
public function render($sTemplate, array $aVars = [])
{
$sTemplate = trim($sTemplate);
// Get the namespace name
$sNamespace = '';
$iSeparatorPosition = strrpos($sTemplate, '::');
if($iSeparatorPosition !== false)
{
$sNamespace = substr($sTemplate, 0, $iSeparatorPosition);
$sTemplate = substr($sTemplate, $iSeparatorPosition + 2);
}
// The default namespace is 'jaxon'
if(!($sNamespace = trim($sNamespace)))
{
$sNamespace = 'jaxon';
}
// Check if the namespace is defined
if(!key_exists($sNamespace, $this->aNamespaces))
{
return false;
}
$aNamespace = $this->aNamespaces[$sNamespace];
// Get the template path
$sTemplatePath = $aNamespace['directory'] . $sTemplate . $aNamespace['extension'];
// Render the template
$xRenderer = new Renderer();
return $xRenderer->render($sTemplatePath, $aVars);
}
|
Render a template
@param string $sTemplate The name of template to be rendered
@param string $aVars The template vars
@return string The template content
|
entailment
|
public static function make($xValue)
{
if($xValue instanceof Interfaces\Parameter)
{
return $xValue;
}
elseif(is_numeric($xValue))
{
return new Parameter(Jaxon::NUMERIC_VALUE, $xValue);
}
elseif(is_string($xValue))
{
return new Parameter(Jaxon::QUOTED_VALUE, $xValue);
}
elseif(is_bool($xValue))
{
return new Parameter(Jaxon::BOOL_VALUE, $xValue);
}
else // if(is_array($xValue) || is_object($xValue))
{
return new Parameter(Jaxon::JS_VALUE, $xValue);
}
}
|
Create a Parameter instance using the given value
@param mixed $xValue The parameter value
@return Parameter
|
entailment
|
public function getScript()
{
$sJsCode = '';
switch($this->sType)
{
case Jaxon::FORM_VALUES:
$sJsCode = $this->getJsCall('getFormValues', $this->xValue);
break;
case Jaxon::INPUT_VALUE:
$sJsCode = $this->getJsCall('$', $this->xValue) . '.value';
break;
case Jaxon::CHECKED_VALUE:
$sJsCode = $this->getJsCall('$', $this->xValue) . '.checked';
break;
case Jaxon::ELEMENT_INNERHTML:
$sJsCode = $this->getJsCall('$', $this->xValue) . '.innerHTML';
break;
case Jaxon::QUOTED_VALUE:
$sJsCode = $this->getQuotedValue(addslashes($this->xValue));
break;
case Jaxon::BOOL_VALUE:
$sJsCode = ($this->xValue) ? 'true' : 'false';
break;
case Jaxon::PAGE_NUMBER:
$sJsCode = (string)$this->xValue;
break;
case Jaxon::NUMERIC_VALUE:
$sJsCode = (string)$this->xValue;
break;
case Jaxon::JS_VALUE:
if(is_array($this->xValue) || is_object($this->xValue))
{
// Unable to use double quotes here because they cannot be handled on client side.
// So we are using simple quotes even if the Json standard recommends double quotes.
$sJsCode = str_replace(['"'], ["'"], json_encode($this->xValue, JSON_HEX_APOS | JSON_HEX_QUOT));
}
else
{
$sJsCode = (string)$this->xValue;
}
break;
}
return $sJsCode;
}
|
Generate the javascript code.
@return string
|
entailment
|
public static function fromHttpData($sUploadDir, array $aFile)
{
$xFile = new UploadedFile();
$xFile->sType = $aFile['type'];
$xFile->sName = $xFile->slugify($aFile['filename']);
$xFile->sFilename = $aFile['name'];
$xFile->sExtension = $aFile['extension'];
$xFile->sSize = $aFile['size'];
$xFile->sPath = $sUploadDir . $xFile->sName . '.' . $xFile->sExtension;
return $xFile;
}
|
Create an instance of this class using data from the $_FILES global var.
@param string $sUploadDir The directory where to save the uploaded file
@param array $aFile The uploaded file data
@return UploadedFile
|
entailment
|
public function toTempData()
{
return [
'type' => $this->sType,
'name' => $this->sName,
'filename' => $this->sFilename,
'extension' => $this->sExtension,
'size' => $this->sSize,
'path' => $this->sPath,
];
}
|
Convert the UploadedFile instance to array.
@return array
|
entailment
|
public static function fromTempData(array $aFile)
{
$xFile = new UploadedFile();
$xFile->sType = $aFile['type'];
$xFile->sName = $aFile['name'];
$xFile->sFilename = $aFile['filename'];
$xFile->sExtension = $aFile['extension'];
$xFile->sSize = $aFile['size'];
$xFile->sPath = $aFile['path'];
return $xFile;
}
|
Create an instance of this class using data from an array.
@param array $aFile The uploaded file data
@return UploadedFile
|
entailment
|
public function configure($sName, $sValue)
{
switch($sName)
{
case 'class': // The user function is a method in the given class
$this->xUserFunction = [$sValue, $this->xUserFunction];
break;
case 'alias':
$this->sJsFunction = $sValue;
break;
case 'include':
$this->sInclude = $sValue;
break;
default:
$this->aConfiguration[$sName] = $sValue;
break;
}
}
|
Set call options for this instance
@param string $sName The name of the configuration option
@param string $sValue The value of the configuration option
@return void
|
entailment
|
public function getScript()
{
$sPrefix = $this->getOption('core.prefix.function');
$sJsFunction = $this->getName();
return $this->render('jaxon::support/function.js', array(
'sPrefix' => $sPrefix,
'sAlias' => $sJsFunction,
'sFunction' => $sJsFunction, // sAlias is the same as sFunction
'aConfig' => $this->aConfiguration,
));
}
|
Generate the javascript function stub that is sent to the browser on initial page load
@return string
|
entailment
|
public function call($aArgs = [])
{
if(($this->sInclude))
{
require_once $this->sInclude;
}
// If the function is an alias for a class method, then instanciate the class
if(is_array($this->xUserFunction) && is_string($this->xUserFunction[0]))
{
$sClassName = $this->xUserFunction[0];
$this->xUserFunction[0] = new $sClassName;
}
return call_user_func_array($this->xUserFunction, $aArgs);
}
|
Call the registered user function, including an external file if needed
and passing along the specified arguments
@param array $aArgs The function arguments
@return void
|
entailment
|
public function title(string $title = null): Htmlable
{
$page = Paginator::resolveCurrentPage();
$data = [
'site' => ['name' => $this->site],
'page' => ['title' => $title, 'number' => $page],
];
$data['site']['name'] = $this->getHtmlTitleFormatForSite($data);
$output = $this->getHtmlTitleFormatForPage($data);
return $this->html->create('title', trim($output));
}
|
Create the title.
@param string|null $title
@return \Illuminate\Contracts\Support\Htmlable
|
entailment
|
protected function getHtmlTitleFormatForSite(array $data)
{
if ((int) $data['page']['number'] < 2) {
return $data['site']['name'];
}
return Str::replace($this->formats['site'], $data);
}
|
Get HTML::title() format for site.
@param array $data
@return mixed
|
entailment
|
protected function getHtmlTitleFormatForPage(array $data)
{
if (empty($data['page']['title'])) {
return $data['site']['name'];
}
return Str::replace($this->formats['page'], $data);
}
|
Get HTML::title() format for page.
@param array $data
@return mixed
|
entailment
|
public function create(string $tag = 'div', $value = null, array $attributes = []): Htmlable
{
if (\is_array($value)) {
$attributes = $value;
$value = null;
}
$content = '<'.$tag.$this->attributes($attributes).'>';
if (! \is_null($value)) {
$content .= $this->entities($value).'</'.$tag.'>';
}
return $this->toHtmlString($content);
}
|
Generate a HTML element.
@param string $tag
@param mixed $value
@param array $attributes
@return \Illuminate\Contracts\Support\Htmlable
|
entailment
|
public function attributable(array $attributes, array $defaults = []): string
{
return $this->attributes($this->decorate($attributes, $defaults));
}
|
Build a list of HTML attributes from one or two array and generate
HTML attributes.
@param array $attributes
@param array $defaults
@return string
|
entailment
|
public function addParameters(array $aParameters)
{
foreach($aParameters as $xParameter)
{
if($xParameter instanceof JsCall)
{
$this->addParameter(Jaxon::JS_VALUE, 'function(){' . $xParameter->getScript() . ';}');
}
else
{
$this->pushParameter(Parameter::make($xParameter));
}
}
}
|
Add a set of parameters to this request
@param array $aParameters The parameters
@return void
|
entailment
|
public function checkboxes($name, array $list = [], $checked = null, array $options = [], $separator = '<br>')
{
$group = [];
$name = \str_replace('[]', '', $name);
foreach ($list as $id => $label) {
$group[] = $this->generateCheckboxByGroup($id, $label, $name, $checked, $options);
}
return \implode($separator, $group);
}
|
Create a checkboxes input field.
@param string $name
@param array $list
@param bool|array $checked
@param array $options
@param string $separator
@return string
|
entailment
|
protected function generateCheckboxByGroup($id, $label, $name, $checked, array $options)
{
$identifier = \sprintf('%s_%s', $name, $id);
$key = \sprintf('%s[]', $name);
$active = \in_array($id, (array) $checked);
$options['id'] = $identifier;
$control = $this->checkbox($key, $id, $active, $options);
$label = $this->label($identifier, $label);
return \implode(' ', [$control, $label]);
}
|
Generate checkbox by group.
@param string $id
@param string $label
@param string $name
@param bool|array $checked
@param array $options
@return array
|
entailment
|
public function render($sPath, array $aVars = [])
{
// Make the template vars available as attributes
foreach($aVars as $sName => $xValue)
{
$sName = (string)$sName;
$this->$sName = $xValue;
}
// Render the template
ob_start();
include($sPath);
$sRendered = ob_get_clean();
return $sRendered;
}
|
Render a template
@param string $sPath The path to the template
@param string $aVars The template vars
@return string The template content
|
entailment
|
public function initiate(array $config): void
{
foreach ($config as $key => $value) {
if (\property_exists($this, $key)) {
$this->{$key} = $value;
}
}
$this->header(function () {
return [];
});
}
|
Load grid configuration.
@param array $config
@return void
|
entailment
|
public function layout(string $name, array $data = [])
{
if (\in_array($name, ['horizontal', 'vertical'])) {
$this->view = "orchestra/html::table.{$name}";
} else {
$this->view = $name;
}
$this->viewData = $data;
return $this;
}
|
Set table layout (view).
<code>
// use default horizontal layout
$table->layout('horizontal');
// use default vertical layout
$table->layout('vertical');
// define table using custom view
$table->layout('path.to.view');
</code>
@param string $name
@param array $data
@return $this
|
entailment
|
public function with($model, bool $paginate = true)
{
$this->model = $model;
$this->paginate = $paginate;
return $this;
}
|
Attach Eloquent as row and allow pagination (if required).
<code>
// add model without pagination
$table->with(User::all(), false);
// add model with pagination
$table->with(User::paginate(30), true);
</code>
@param mixed $model
@param bool $paginate
@throws \InvalidArgumentException
@return $this
|
entailment
|
public function rows($data)
{
if ($data instanceof Arrayable) {
$data = $data->toArray();
}
$this->setRowsData($data);
return $this;
}
|
Attach rows data instead of assigning a model.
<code>
// assign a data
$table->rows(DB::table('users')->get());
</code>
@param array|\Illuminate\Contracts\Support\Arrayable $data
@throws \InvalidArgumentException
@return $this
|
entailment
|
public function data(): array
{
if (empty($this->data) && ! empty($this->model)) {
$this->buildRowsFromModel($this->model);
}
return $this->data;
}
|
Get raw data.
@throws \InvalidArgumentException
@return array
|
entailment
|
public function header(Closure $callback = null)
{
if (\is_null($callback)) {
return $this->header;
}
$this->header = $callback;
return null;
}
|
Add or append grid header attributes.
@param \Closure|null $callback
@return \Closure|array|null
|
entailment
|
public function column($name, $callback = null)
{
list($name, $column) = $this->buildColumn($name, $callback);
$this->columns[] = $column;
$this->keyMap[$name] = \count($this->columns) - 1;
return $column;
}
|
Append a new column to the table.
<code>
// add a new column using just field name
$table->column('username');
// add a new column using a label (header title) and field name
$table->column('User Name', 'username');
// add a new column by using a field name and closure
$table->column('fullname', function ($column)
{
$column->label = 'User Name';
$column->value = function ($row) {
return $row->first_name.' '.$row->last_name;
};
$column->attributes(function ($row) {
return array('data-id' => $row->id);
});
});
</code>
@param mixed $name
@param mixed|null $callback
@return \Orchestra\Contracts\Html\Table\Column
|
entailment
|
public function find(string $name): Column
{
if (! \array_key_exists($name, $this->keyMap)) {
throw new InvalidArgumentException("Name [{$name}] is not available.");
}
return $this->columns[$this->keyMap[$name]];
}
|
Find definition that match the given id.
@param string $name
@throws \InvalidArgumentException
@return \Orchestra\Contracts\Html\Table\Column
|
entailment
|
public function paginate($perPage)
{
if (\filter_var($perPage, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) && ! \is_bool($perPage)) {
$this->perPage = $perPage;
$this->paginate = true;
} elseif (\filter_var($perPage, FILTER_VALIDATE_BOOLEAN)) {
$this->perPage = null;
$this->paginate = $perPage;
} else {
$this->perPage = null;
$this->paginate = false;
}
return $this;
}
|
Setup pagination.
@param bool|int|null $perPage
@return $this
|
entailment
|
public function searchable(array $attributes, string $key = 'q'): void
{
$model = $this->resolveQueryBuilderFromModel($this->model);
$request = $this->app->make('request');
$value = $request->input($key);
$request->merge(["{$key}" => \rawurlencode($value)]);
$this->set('search', [
'attributes' => $attributes,
'key' => $key,
'value' => $value,
]);
$this->model = $this->setupWildcardQueryFilter($model, $value, $attributes);
}
|
Execute searchable filter on model instance.
@param array $attributes
@param string $key
@return void
|
entailment
|
public function sortable(
array $orderColumns = [],
string $orderByKey = 'order_by',
string $directionKey = 'direction'
): void {
$model = $this->resolveQueryBuilderFromModel($this->model);
$request = $this->app->make('request');
$orderByValue = $request->input($orderByKey);
$directionValue = $request->input($directionKey);
$this->set('filter.order_by', ['key' => $orderByKey, 'value' => $orderByValue]);
$this->set('filter.direction', ['key' => $directionKey, 'value' => $directionValue]);
$this->set('filter.columns', $orderColumns);
$this->model = $this->setupBasicQueryFilter($model, [
'order_by' => $orderByValue,
'direction' => $directionValue,
'columns' => $orderColumns,
]);
}
|
Execute sortable query filter on model instance.
@param array $orderColumns
@param string $orderByKey
@param string $directionKey
@return void
|
entailment
|
protected function buildColumn($name, $callback = null): array
{
list($label, $name, $callback) = $this->buildFluentAttributes($name, $callback);
$value = '';
if (! empty($name)) {
$value = function ($row) use ($name) {
return \data_get($row, $name);
};
}
$column = new Column([
'id' => $name,
'label' => $label,
'value' => $value,
'headers' => [],
'attributes' => function ($row) {
return [];
},
]);
if (\is_callable($callback)) {
$callback($column);
}
return [$name, $column];
}
|
Build control.
@param mixed $name
@param mixed $callback
@return array
|
entailment
|
protected function buildModel($model)
{
try {
$query = $this->resolveQueryBuilderFromModel($model);
} catch (InvalidArgumentException $e) {
$query = $model;
}
if ($this->paginate === true && \method_exists($query, 'paginate')) {
$query = $query->paginate($this->perPage, ['*'], $this->pageName);
} elseif ($this->isQueryBuilder($query)) {
$query = $query->get();
}
return $query;
}
|
Convert the model to Paginator when available or convert it
to a collection.
@param mixed $model
@return \Illuminate\Contracts\Support\Arrayable|array
|
entailment
|
protected function buildRowsFromModel($model): void
{
$this->model = $model = $this->buildModel($model);
if ($model instanceof Paginator) {
$this->setRowsData($model->items());
$this->paginate = true;
} elseif ($model instanceof Collection) {
$this->setRowsData($model->all());
} elseif ($model instanceof Arrayable) {
$this->setRowsData($model->toArray());
} elseif (\is_array($model)) {
$this->setRowsData($model);
} else {
throw new InvalidArgumentException('Unable to convert $model to array.');
}
}
|
Get rows from model instance.
@param object $model
@throws \InvalidArgumentException
@return void
|
entailment
|
protected function resolveQueryBuilderFromModel($model)
{
if ($this->isEloquentModel($model)) {
return $model->newQuery();
} elseif ($this->isEloquentRelationModel($model)) {
return $model->getQuery();
} elseif (! $this->isQueryBuilder($model)) {
throw new InvalidArgumentException('Unable to load Query Builder from $model');
}
return $model;
}
|
Resolve query builder from model instance.
@param mixed $model
@throws \InvalidArgumentException
@return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
|
entailment
|
protected function isQueryBuilder($model): bool
{
return $model instanceof \Illuminate\Database\Query\Builder
|| $model instanceof \Illuminate\Database\Eloquent\Builder;
}
|
Check if given $model is a query builder.
@param mixed $model
@return bool
|
entailment
|
public function getPages()
{
$pages = [];
if($this->numPages <= 1)
{
return [];
}
if($this->numPages <= $this->maxPagesToShow)
{
for($i = 1; $i <= $this->numPages; $i++)
{
$pages[] = $this->createPage($i, $i == $this->currentPage);
}
}
else
{
// Determine the sliding range, centered around the current page.
$numAdjacents = (int) floor(($this->maxPagesToShow - 3) / 2);
if($this->currentPage + $numAdjacents > $this->numPages)
{
$slidingStart = $this->numPages - $this->maxPagesToShow + 2;
}
else
{
$slidingStart = $this->currentPage - $numAdjacents;
}
if($slidingStart < 2)
{
$slidingStart = 2;
}
$slidingEnd = $slidingStart + $this->maxPagesToShow - 3;
if($slidingEnd >= $this->numPages)
{
$slidingEnd = $this->numPages - 1;
}
// Build the list of pages.
$pages[] = $this->createPage(1, $this->currentPage == 1);
if($slidingStart > 2)
{
$pages[] = $this->createPageEllipsis();
}
for($i = $slidingStart; $i <= $slidingEnd; $i++)
{
$pages[] = $this->createPage($i, $i == $this->currentPage);
}
if($slidingEnd < $this->numPages - 1)
{
$pages[] = $this->createPageEllipsis();
}
$pages[] = $this->createPage($this->numPages, $this->currentPage == $this->numPages);
}
return $pages;
}
|
Get an array of paginated page data.
Example:
array(
array ('num' => 1, 'call' => '/example/page/1', 'isCurrent' => false),
array ('num' => '...', 'call' => NULL, 'isCurrent' => false),
array ('num' => 3, 'call' => '/example/page/3', 'isCurrent' => false),
array ('num' => 4, 'call' => '/example/page/4', 'isCurrent' => true ),
array ('num' => 5, 'call' => '/example/page/5', 'isCurrent' => false),
array ('num' => '...', 'call' => NULL, 'isCurrent' => false),
array ('num' => 10, 'call' => '/example/page/10', 'isCurrent' => false),
)
@return array
|
entailment
|
public function toHtml()
{
if($this->getNumPages() <= 1)
{
return '';
}
$this->renderer->setPaginator($this);
return $this->renderer->render();
}
|
Render an HTML pagination control.
@return string
|
entailment
|
private function __convertStringToBool($sValue)
{
if(strcasecmp($sValue, 'true') == 0)
{
return true;
}
if(strcasecmp($sValue, 'false') == 0)
{
return false;
}
if(is_numeric($sValue))
{
if($sValue == 0)
{
return false;
}
return true;
}
return false;
}
|
Converts a string to a boolean var
@param string $sValue The string to be converted
@return boolean
|
entailment
|
private function __convertValue($sValue)
{
$cType = substr($sValue, 0, 1);
$sValue = substr($sValue, 1);
switch ($cType)
{
case 'S':
$value = ($sValue === false ? '' : $sValue);
break;
case 'B':
$value = $this->__convertStringToBool($sValue);
break;
case 'N':
$value = ($sValue == floor($sValue) ? (int)$sValue : (float)$sValue);
break;
case '*':
default:
$value = null;
break;
}
return $value;
}
|
Convert an Jaxon request argument to its value
Depending of its first char, the Jaxon request argument is converted to a given type.
@param string $sValue The keys of the options in the file
@return mixed
|
entailment
|
private function __argumentDecode(&$sArg)
{
if($sArg == '')
{
return '';
}
// Arguments are url encoded when uploading files
$sType = 'multipart/form-data';
$iLen = strlen($sType);
$sContentType = '';
if(key_exists('CONTENT_TYPE', $_SERVER))
{
$sContentType = substr($_SERVER['CONTENT_TYPE'], 0, $iLen);
}
elseif(key_exists('HTTP_CONTENT_TYPE', $_SERVER))
{
$sContentType = substr($_SERVER['HTTP_CONTENT_TYPE'], 0, $iLen);
}
if($sContentType == $sType)
{
$sArg = urldecode($sArg);
}
$data = json_decode($sArg, true);
if($data !== null && $sArg != $data)
{
$sArg = $data;
}
else
{
$sArg = $this->__convertValue($sArg);
}
}
|
Decode and convert an Jaxon request argument from JSON
@param string $sArg The Jaxon request argument
@return mixed
|
entailment
|
private function __argumentDecodeUTF8_iconv(&$mArg)
{
if(is_array($mArg))
{
foreach($mArg as $sKey => &$xArg)
{
$sNewKey = $sKey;
$this->__argumentDecodeUTF8_iconv($sNewKey);
if($sNewKey != $sKey)
{
$mArg[$sNewKey] = $xArg;
unset($mArg[$sKey]);
$sKey = $sNewKey;
}
$this->__argumentDecodeUTF8_iconv($xArg);
}
}
elseif(is_string($mArg))
{
$mArg = iconv("UTF-8", $this->getOption('core.encoding') . '//TRANSLIT', $mArg);
}
}
|
Decode an Jaxon request argument and convert to UTF8 with iconv
@param string|array $mArg The Jaxon request argument
@return void
|
entailment
|
private function __argumentDecodeUTF8_mb_convert_encoding(&$mArg)
{
if(is_array($mArg))
{
foreach($mArg as $sKey => &$xArg)
{
$sNewKey = $sKey;
$this->__argumentDecodeUTF8_mb_convert_encoding($sNewKey);
if($sNewKey != $sKey)
{
$mArg[$sNewKey] = $xArg;
unset($mArg[$sKey]);
$sKey = $sNewKey;
}
$this->__argumentDecodeUTF8_mb_convert_encoding($xArg);
}
}
elseif(is_string($mArg))
{
$mArg = mb_convert_encoding($mArg, $this->getOption('core.encoding'), "UTF-8");
}
}
|
Decode an Jaxon request argument and convert to UTF8 with mb_convert_encoding
@param string|array $mArg The Jaxon request argument
@return void
|
entailment
|
private function __argumentDecodeUTF8_utf8_decode(&$mArg)
{
if(is_array($mArg))
{
foreach($mArg as $sKey => &$xArg)
{
$sNewKey = $sKey;
$this->__argumentDecodeUTF8_utf8_decode($sNewKey);
if($sNewKey != $sKey)
{
$mArg[$sNewKey] = $xArg;
unset($mArg[$sKey]);
$sKey = $sNewKey;
}
$this->__argumentDecodeUTF8_utf8_decode($xArg);
}
}
elseif(is_string($mArg))
{
$mArg = utf8_decode($mArg);
}
}
|
Decode an Jaxon request argument from UTF8
@param string|array $mArg The Jaxon request argument
@return void
|
entailment
|
public function processArguments()
{
if(($this->getOption('core.decode_utf8')))
{
$sFunction = '';
if(function_exists('iconv'))
{
$sFunction = "iconv";
}
elseif(function_exists('mb_convert_encoding'))
{
$sFunction = "mb_convert_encoding";
}
elseif($this->getOption('core.encoding') == "ISO-8859-1")
{
$sFunction = "utf8_decode";
}
else
{
throw new \Jaxon\Exception\Error($this->trans('errors.request.conversion'));
}
$mFunction = array(&$this, '__argumentDecodeUTF8_' . $sFunction);
array_walk($this->aArgs, $mFunction);
$this->setOption('core.decode_utf8', false);
}
return $this->aArgs;
}
|
Return the array of arguments that were extracted and parsed from the GET or POST data
@return array
|
entailment
|
public function canProcessRequest()
{
foreach($this->xPluginManager->getRequestPlugins() as $xPlugin)
{
if($xPlugin->getName() != Jaxon::FILE_UPLOAD && $xPlugin->canProcessRequest())
{
return true;
}
}
return false;
}
|
Check if the current request can be processed
Calls each of the request plugins and determines if the current request can be processed by one of them.
If no processor identifies the current request, then the request must be for the initial page load.
@return boolean
|
entailment
|
public function processRequest()
{
foreach($this->xPluginManager->getRequestPlugins() as $xPlugin)
{
if($xPlugin->getName() != Jaxon::FILE_UPLOAD && $xPlugin->canProcessRequest())
{
$xUploadPlugin = $this->xPluginManager->getRequestPlugin(Jaxon::FILE_UPLOAD);
// Process uploaded files
if($xUploadPlugin != null)
{
$xUploadPlugin->processRequest();
}
// Process the request
return $xPlugin->processRequest();
}
}
// Todo: throw an exception
return false;
}
|
Process the current request
Calls each of the request plugins to request that they process the current request.
If any plugin processes the request, it will return true.
@return boolean
|
entailment
|
public function register($sType, $sDirectory, $aOptions)
{
if($sType != $this->getName())
{
return false;
}
if(!is_string($sDirectory) || !is_dir($sDirectory))
{
throw new \Jaxon\Exception\Error($this->trans('errors.objects.invalid-declaration'));
}
if(is_string($aOptions))
{
$aOptions = ['namespace' => $aOptions];
}
if(!is_array($aOptions))
{
throw new \Jaxon\Exception\Error($this->trans('errors.objects.invalid-declaration'));
}
$sDirectory = rtrim(trim($sDirectory), DIRECTORY_SEPARATOR);
if(!is_dir($sDirectory))
{
return false;
}
$aOptions['directory'] = realpath($sDirectory);
$sNamespace = key_exists('namespace', $aOptions) ? $aOptions['namespace'] : '';
if(!($sNamespace = trim($sNamespace, ' \\')))
{
$sNamespace = '';
}
// $sSeparator = key_exists('separator', $aOptions) ? $aOptions['separator'] : '.';
// // Only '.' and '_' are allowed to be used as separator. Any other value is ignored and '.' is used instead.
// if(($sSeparator = trim($sSeparator)) != '_')
// {
// $sSeparator = '.';
// }
// Change the keys in $aOptions to have "\" as separator
$_aOptions = [];
foreach($aOptions as $sName => $aOption)
{
$sName = trim(str_replace('.', '\\', $sName), ' \\');
$_aOptions[$sName] = $aOption;
}
$aOptions = $_aOptions;
if(($sNamespace))
{
// Register the dir with PSR4 autoloading
if(($this->xAutoloader))
{
$this->xAutoloader->setPsr4($sNamespace . '\\', $sDirectory);
}
$this->xRepository->addNamespace($sNamespace, $aOptions);
}
else
{
// Use underscore as separator, so there's no need to deal with namespace
// when generating javascript code.
$aOptions['separator'] = '_';
$aOptions['autoload'] = $this->bAutoloadEnabled;
$this->xRepository->addDirectory($sDirectory, $aOptions);
}
return true;
}
|
Register a callable class
@param string $sType The type of request handler being registered
@param string $sDirectory The name of the class being registered
@param array|string $aOptions The associated options
@return boolean
|
entailment
|
public function read($sConfigFile)
{
$sExt = pathinfo($sConfigFile, PATHINFO_EXTENSION);
switch($sExt)
{
case 'php':
$aConfigOptions = Php::read($sConfigFile);
break;
case 'yaml':
case 'yml':
$aConfigOptions = Yaml::read($sConfigFile);
break;
case 'json':
$aConfigOptions = Json::read($sConfigFile);
break;
default:
$sErrorMsg = jaxon_trans('config.errors.file.extension', array('path' => $sConfigFile));
throw new \Jaxon\Config\Exception\File($sErrorMsg);
}
return $aConfigOptions;
}
|
Read options from a config file
@param string $sConfigFile The full path to the config file
@return array
|
entailment
|
abstract public function __construct(Request $request, Translator $translator, View $view, GridContract $grid);
/**
* Extend decoration.
*
* @param callable $callback
*
* @return $this
*/
public function extend(callable $callback = null)
{
// Run the table designer.
if (! \is_null($callback)) {
\call_user_func($callback, $this->grid, $this->request, $this->translator);
}
return $this;
}
|
Create a new Builder instance.
@param \Illuminate\Http\Request $request
@param \Illuminate\Translation\Translator $translator
@param \Illuminate\Contracts\View\Factory $view
@param \Orchestra\Contracts\Html\Grid $grid
|
entailment
|
public static function detect()
{
$aURL = [];
// Try to get the request URL
if(!empty($_SERVER['REQUEST_URI']))
{
$_SERVER['REQUEST_URI'] = str_replace(array('"',"'",'<','>'), array('%22','%27','%3C','%3E'), $_SERVER['REQUEST_URI']);
$aURL = parse_url($_SERVER['REQUEST_URI']);
}
// Fill in the empty values
if(empty($aURL['scheme']))
{
if(!empty($_SERVER['HTTP_SCHEME']))
{
$aURL['scheme'] = $_SERVER['HTTP_SCHEME'];
}
else
{
$aURL['scheme'] = ((!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http');
}
}
if(empty($aURL['host']))
{
if(!empty($_SERVER['HTTP_X_FORWARDED_HOST']))
{
if(strpos($_SERVER['HTTP_X_FORWARDED_HOST'], ':') > 0)
{
list($aURL['host'], $aURL['port']) = explode(':', $_SERVER['HTTP_X_FORWARDED_HOST']);
}
else
{
$aURL['host'] = $_SERVER['HTTP_X_FORWARDED_HOST'];
}
}
elseif(!empty($_SERVER['HTTP_HOST']))
{
if(strpos($_SERVER['HTTP_HOST'], ':') > 0)
{
list($aURL['host'], $aURL['port']) = explode(':', $_SERVER['HTTP_HOST']);
}
else
{
$aURL['host'] = $_SERVER['HTTP_HOST'];
}
}
elseif(!empty($_SERVER['SERVER_NAME']))
{
$aURL['host'] = $_SERVER['SERVER_NAME'];
}
else
{
throw new \Jaxon\Exception\URI();
}
}
if(empty($aURL['port']) && !empty($_SERVER['SERVER_PORT']))
{
$aURL['port'] = $_SERVER['SERVER_PORT'];
}
if(!empty($aURL['path']) && strlen(basename($aURL['path'])) == 0)
{
unset($aURL['path']);
}
if(empty($aURL['path']))
{
if(!empty($_SERVER['PATH_INFO']))
{
$sPath = parse_url($_SERVER['PATH_INFO']);
}
else
{
$sPath = parse_url($_SERVER['PHP_SELF']);
}
if(isset($sPath['path']))
{
$aURL['path'] = str_replace(array('"',"'",'<','>'), array('%22','%27','%3C','%3E'), $sPath['path']);
}
unset($sPath);
}
if(empty($aURL['query']) && !empty($_SERVER['QUERY_STRING']))
{
$aURL['query'] = $_SERVER['QUERY_STRING'];
}
if(!empty($aURL['query']))
{
$aURL['query'] = '?'.$aURL['query'];
}
// Build the URL: Start with scheme, user and pass
$sURL = $aURL['scheme'].'://';
if(!empty($aURL['user']))
{
$sURL.= $aURL['user'];
if(!empty($aURL['pass']))
{
$sURL.= ':'.$aURL['pass'];
}
$sURL.= '@';
}
// Add the host
$sURL.= $aURL['host'];
// Add the port if needed
if(!empty($aURL['port'])
&& (($aURL['scheme'] == 'http' && $aURL['port'] != 80)
|| ($aURL['scheme'] == 'https' && $aURL['port'] != 443)))
{
$sURL.= ':'.$aURL['port'];
}
// Add the path and the query string
$sURL.= $aURL['path'].@$aURL['query'];
// Clean up
unset($aURL);
$aURL = explode("?", $sURL);
if(1 < count($aURL))
{
$aQueries = explode("&", $aURL[1]);
foreach($aQueries as $sKey => $sQuery)
{
if("jxnGenerate" == substr($sQuery, 0, 11))
unset($aQueries[$sKey]);
}
$sQueries = implode("&", $aQueries);
$aURL[1] = $sQueries;
$sURL = implode("?", $aURL);
}
return $sURL;
}
|
Detect the URI of the current request
@return string The URI
|
entailment
|
private function init($sTranslationDir, $sTemplateDir)
{
/*
* Parameters
*/
// Translation directory
$this->coreContainer['jaxon.core.translation_dir'] = $sTranslationDir;
// Template directory
$this->coreContainer['jaxon.core.template_dir'] = $sTemplateDir;
/*
* Core library objects
*/
// Jaxon Core
$this->coreContainer[Jaxon::class] = function () {
return new Jaxon();
};
// Global Response
$this->coreContainer[Response::class] = function () {
return new Response();
};
// Dialog
$this->coreContainer[Dialog::class] = function () {
return new Dialog();
};
/*
* Managers
*/
// Callable objects repository
$this->coreContainer[CallableRepository::class] = function () {
return new CallableRepository();
};
// Plugin Manager
$this->coreContainer[PluginManager::class] = function () {
return new PluginManager();
};
// Request Handler
$this->coreContainer[RequestHandler::class] = function ($c) {
return new RequestHandler($c[PluginManager::class]);
};
// Request Factory
$this->coreContainer[RequestFactory::class] = function ($c) {
return new RequestFactory($c[CallableRepository::class]);
};
// Response Manager
$this->coreContainer[ResponseManager::class] = function () {
return new ResponseManager();
};
// Code Generator
$this->coreContainer[CodeGenerator::class] = function ($c) {
return new CodeGenerator($c[PluginManager::class]);
};
/*
* Config
*/
$this->coreContainer[Config::class] = function () {
return new Config();
};
$this->coreContainer[ConfigReader::class] = function () {
return new ConfigReader();
};
/*
* Services
*/
// Minifier
$this->coreContainer[Minifier::class] = function () {
return new Minifier();
};
// Translator
$this->coreContainer[Translator::class] = function ($c) {
return new Translator($c['jaxon.core.translation_dir'], $c[Config::class]);
};
// Template engine
$this->coreContainer[Template::class] = function ($c) {
return new Template($c['jaxon.core.template_dir']);
};
// Validator
$this->coreContainer[Validator::class] = function ($c) {
return new Validator($c[Translator::class], $c[Config::class]);
};
// Pagination Renderer
$this->coreContainer[PaginationRenderer::class] = function ($c) {
return new PaginationRenderer($c[Template::class]);
};
// Pagination Paginator
$this->coreContainer[Paginator::class] = function ($c) {
return new Paginator($c[PaginationRenderer::class]);
};
// Event Dispatcher
$this->coreContainer[EventDispatcher::class] = function () {
return new EventDispatcher();
};
// View Renderer Facade
// $this->coreContainer[\Jaxon\Sentry\View\Facade::class] = function ($c) {
// $aRenderers = $c['jaxon.view.data.renderers'];
// $sDefaultNamespace = $c['jaxon.view.data.namespace.default'];
// return new \Jaxon\Sentry\View\Facade($aRenderers, $sDefaultNamespace);
// };
}
|
Set the parameters and create the objects in the dependency injection container
@param string $sTranslationDir The translation directory
@param string $sTemplateDir The template directory
@return void
|
entailment
|
public function get($sClass)
{
if($this->sentryContainer != null && $this->sentryContainer->has($sClass))
{
return $this->sentryContainer->get($sClass);
}
return $this->coreContainer[$sClass];
}
|
Get a class instance
@return object The class instance
|
entailment
|
public function addViewRenderer($sId, $xClosure)
{
// Return the non-initialiazed view renderer
$this->coreContainer['jaxon.sentry.view.base.' . $sId] = $xClosure;
// Return the initialized view renderer
$this->coreContainer['jaxon.sentry.view.' . $sId] = function ($c) use ($sId) {
// Get the defined renderer
$renderer = $c['jaxon.sentry.view.base.' . $sId];
// Init the renderer with the template namespaces
$aNamespaces = $this->coreContainer['jaxon.view.data.namespaces'];
if(key_exists($sId, $aNamespaces))
{
foreach($aNamespaces[$sId] as $ns)
{
$renderer->addNamespace($ns['namespace'], $ns['directory'], $ns['extension']);
}
}
return $renderer;
};
}
|
Add a view renderer
@param string $sId The unique identifier of the view renderer
@param Closure $xClosure A closure to create the view instance
@return void
|
entailment
|
public function getViewRenderer($sId = '')
{
if(!$sId)
{
// Return the view renderer facade
return $this->coreContainer[\Jaxon\Sentry\View\Facade::class];
}
// Return the view renderer with the given id
return $this->coreContainer['jaxon.sentry.view.' . $sId];
}
|
Get the view renderer
@param string $sId The unique identifier of the view renderer
@return Jaxon\Sentry\Interfaces\View
|
entailment
|
public function canExportJavascript()
{
// Check config options
// - The js.app.extern option must be set to true
// - The js.app.uri and js.app.dir options must be set to non null values
if(!$this->getOption('js.app.extern') ||
!$this->getOption('js.app.uri') ||
!$this->getOption('js.app.dir'))
{
return false;
}
// Check dir access
// - The js.app.dir must be writable
$sJsAppDir = $this->getOption('js.app.dir');
if(!is_dir($sJsAppDir) || !is_writable($sJsAppDir))
{
return false;
}
return true;
}
|
Check if the javascript code generated by Jaxon can be exported to an external file
@return boolean
|
entailment
|
private function generateHash()
{
$sHash = jaxon()->getVersion();
foreach($this->xPluginManager->getRequestPlugins() as $xPlugin)
{
$sHash .= $xPlugin->generateHash();
}
foreach($this->xPluginManager->getResponsePlugins() as $xPlugin)
{
$sHash .= $xPlugin->generateHash();
}
return md5($sHash);
}
|
Generate a hash for all the javascript code generated by the library
@return string
|
entailment
|
private function makePluginsCode()
{
if($this->sCssCode === null || $this->sJsCode === null || $this->sJsReady === null)
{
$this->sCssCode = '';
$this->sJsCode = '';
$this->sJsReady = '';
foreach($this->xPluginManager->getResponsePlugins() as $xResponsePlugin)
{
if(($sCssCode = trim($xResponsePlugin->getCss())))
{
$this->sCssCode .= rtrim($sCssCode, " \n") . "\n";
}
if(($sJsCode = trim($xResponsePlugin->getJs())))
{
$this->sJsCode .= rtrim($sJsCode, " \n") . "\n";
}
if(($sJsReady = trim($xResponsePlugin->getScript())))
{
$this->sJsReady .= trim($sJsReady, " \n") . "\n";
}
}
$this->sJsReady = $this->render('jaxon::plugins/ready.js', ['sPluginScript' => $this->sJsReady]);
foreach($this->xPluginManager->getRequestPlugins() as $xRequestPlugin)
{
if(($sJsReady = trim($xRequestPlugin->getScript())))
{
$this->sJsReady .= trim($sJsReady, " \n") . "\n";
}
}
foreach($this->xPluginManager->getPackages() as $sPackageClass)
{
$xPackage = jaxon()->di()->get($sPackageClass);
if(($sCssCode = trim($xPackage->css())))
{
$this->sCssCode .= rtrim($sCssCode, " \n") . "\n";
}
if(($sJsCode = trim($xPackage->js())))
{
$this->sJsCode .= rtrim($sJsCode, " \n") . "\n";
}
if(($sJsReady = trim($xPackage->ready())))
{
$this->sJsReady .= trim($sJsReady, " \n") . "\n";
}
}
}
}
|
Get the HTML tags to include Jaxon javascript files into the page
@return string
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.