code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public function getDataGrid(Action $action, FamilyInterface $family): DataGrid
{
return $this->dataGridRegistry->getDataGrid($this->getDataGridConfigCode($action, $family));
}
|
@param Action $action
@param FamilyInterface $family
@return DataGrid
|
protected function getOptions(ProcessState $state)
{
$options = parent::getOptions($state);
$options['criteria'] = $state->getInput();
$options['allow_reset'] = true;
return $options;
}
|
@param ProcessState $state
@throws \Symfony\Component\OptionsResolver\Exception\ExceptionInterface
@return array
|
public function getDefaultFormOptions(Action $action, Request $request, $dataId = null): array
{
$formOptions = parent::getDefaultFormOptions($action, $request, $dataId);
$formOptions['show_legend'] = false;
if ($request->isXmlHttpRequest()) { // Target should not be used when not calling through Ajax
$target = $this->getTarget($request);
if (null !== $target) {
$formOptions['attr']['data-target-element'] = $target;
}
}
$formOptions['label'] = $this->tryTranslate(
[
"admin.{$action->getAdmin()->getCode()}.{$action->getCode()}.title",
"admin.action.{$action->getCode()}.title",
],
[],
ucfirst($action->getCode())
);
return $formOptions;
}
|
{@inheritdoc}
|
public function apply(
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
string $resourceClass,
string $operationName = null
) {
$request = $this->requestStack->getCurrentRequest();
if (null === $request) {
return;
}
$requestProperties = $this->extractProperties($request);
if (!array_key_exists('order', $requestProperties)) {
return;
}
/** @var array $orderProperties */
$orderProperties = $requestProperties['order'];
$this->doApply($queryBuilder, $orderProperties, $resourceClass, $operationName);
}
|
{@inheritdoc}
@throws \Sidus\EAVModelBundle\Exception\MissingFamilyException
@throws \UnexpectedValueException
@throws \LogicException
@throws \ApiPlatform\Core\Exception\InvalidArgumentException
|
protected function filterAttribute(
EAVQueryBuilderInterface $eavQb,
AttributeQueryBuilderInterface $attributeQueryBuilder,
$value,
$strategy = null,
string $operationName = null
) {
$direction = strtoupper((empty($value) && $strategy) ? $strategy : $value);
if (!\in_array($direction, ['ASC', 'DESC'], true)) {
return;
}
$eavQb->addOrderBy($attributeQueryBuilder, $value);
}
|
{@inheritdoc}
|
public function vote(TokenInterface $token, $object, array $attributes)
{
if ($object instanceof DataInterface) {
return $this->familyVoter->vote($token, $object->getFamily(), $attributes);
}
return VoterInterface::ACCESS_ABSTAIN;
}
|
{@inheritdoc}
@throws \Exception
|
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add(
'familyCode',
FamilySelectorType::class,
[
'label' => false,
'placeholder' => 'permission.family.placeholder',
'horizontal_input_wrapper_class' => 'col-sm-12',
]
);
foreach (FamilyPermission::getPermissions() as $permission) {
$builder->add(
$permission,
CheckboxType::class,
[
'widget_checkbox_label' => 'widget',
'horizontal_input_wrapper_class' => 'col-sm-1',
]
);
}
$builder->get('familyCode')->addModelTransformer(
new CallbackTransformer(
function ($originalData) {
if (null === $originalData) {
return null;
}
// Ignoring missing family
if (!$this->familyRegistry->hasFamily($originalData)) {
return null;
}
return $this->familyRegistry->getFamily($originalData);
},
function ($submittedData) {
if ($submittedData instanceof FamilyInterface) {
return $submittedData->getCode();
}
return $submittedData;
}
)
);
}
|
@param FormBuilderInterface $builder
@param array $options
@throws \Symfony\Component\Form\Exception\InvalidArgumentException
@throws \Sidus\EAVModelBundle\Exception\MissingFamilyException
|
public function equals($object)
{
if (!($object instanceof self) || !self::compatibles(get_class($object), static::class)) {
return false;
}
return $this->value() == $object->value();
}
|
Checks if two enums are equal. Value and class are both matched.
Value check is not type strict.
@param mixed $object
@return bool True if enums are equal
|
public static function labels()
{
self::bootClass();
$result = [];
foreach (static::values() as $value) {
$result[] = static::getLabel($value);
}
return $result;
}
|
Returns the array of labels.
@return array
|
public static function choices()
{
self::bootClass();
$result = [];
foreach (static::values() as $value) {
$result[$value] = static::getLabel($value);
}
return $result;
}
|
Returns an array of value => label pairs.
Ready to pass to dropdowns.
Example:
```
const FOO = 'foo';
const BAR = 'bar'
protected static $labels = [
self::FOO => 'I am foo',
self::BAR => 'I am bar'
];
```
self::choices returns:
```
[
'foo' => 'I am foo',
'bar' => 'I am bar'
]
```
@return array
|
private static function bootClass()
{
if (!array_key_exists(static::class, self::$meta)) {
self::$meta[static::class] = (new \ReflectionClass(static::class))->getConstants();
unset(self::$meta[static::class]['__default']);
if (method_exists(static::class, 'boot')) {
static::boot();
}
}
}
|
Initializes the constants array for the class if necessary.
|
private static function compatibles($class1, $class2)
{
if ($class1 == $class2) {
return true;
} elseif (is_subclass_of($class1, $class2)) {
return true;
} elseif (is_subclass_of($class2, $class1)) {
return true;
}
return false;
}
|
Returns whether two enum classes are compatible (are the same type or one descends from the other).
@param string $class1
@param string $class2
@return bool
|
private static function getLabel($value)
{
self::bootClass();
if (static::hasLabels() && isset(static::$labels[$value])) {
return (string) static::$labels[$value];
}
return (string) $value;
}
|
Returns the label for a given value.
!!Make sure it only gets called after bootClass()!!
@param $value
@return string
|
public function getContainerAttributes(Widget $widget): Attributes
{
$attributes = parent::getContainerAttributes($widget);
$attributes->addClass('form-group');
return $attributes;
}
|
{@inheritDoc}
|
public function getControlAttributes(Widget $widget): Attributes
{
$attributes = parent::getControlAttributes($widget);
if (!array_key_exists('form_control', $this->widgetConfig[$widget->type])
|| $this->widgetConfig[$widget->type]['form_control']) {
$attributes->addClass('form-control');
}
if (!$widget->controlClass && $this->widgetConfig[$widget->type]['control_class']) {
$attributes->addClass($this->widgetConfig[$widget->type]['control_class']);
}
if ($widget->hasErrors()) {
$attributes->addClass('is-invalid');
}
return $attributes;
}
|
{@inheritDoc}
|
public function getInputGroup(Widget $widget)
{
if ($this->widgetConfig[$widget->type]['input_group'] && $widget->bs_addInputGroup) {
return InputGroupHelper::forWidget($widget);
}
return null;
}
|
Get the input group.
@param Widget $widget Widget.
@return InputGroupHelper
|
protected function getTemplate(Widget $widget, string $section): string
{
if ($section === 'help' && empty($this->widgetConfig[$widget->type]['help'])) {
return '';
}
if (isset($this->widgetConfig[$widget->type]['templates'][$section])) {
return $this->widgetConfig[$widget->type]['templates'][$section];
}
if (isset($this->fallbackConfig['templates'][$section])) {
return $this->fallbackConfig['templates'][$section];
}
return '';
}
|
Get a template for a section.
@param Widget $widget Widget.
@param string $section Section.
@return string
|
public function getBundles(ParserInterface $parser)
{
return [
BundleConfig::create(ContaoBootstrapFormBundle::class)
->setLoadAfter(
[
ContaoCoreBundle::class,
ContaoBootstrapCoreBundle::class,
NetzmachtContaoFormDesignerBundle::class,
]
),
];
}
|
{@inheritDoc}
|
public function dispatch($requestBody = null)
{
if($requestBody===null){
$requestBody = $_POST;
}
if(empty($requestBody)){
throw new HandlerException('Payload empty', HandlerException::PAYLOAD_EMPTY);
}
// no action specified?
if(empty($requestBody['action'])){
throw new HandlerException('Action not exists', HandlerException::ACTION_NOT_EXISTS);
}
// validate if specified action exists
$this->actionExists($requestBody['action']);
// calculate hash payload
$this->verifyPayload($requestBody);
// fire handlers for specified actions
$this->fire($requestBody['action'], $requestBody);
}
|
{@inheritdoc}
|
public function verifyPayload($payload)
{
$providedHash = $payload['hash'];
unset($payload['hash']);
// sort params
ksort($payload);
$processedPayload = "";
foreach($payload as $k => $v){
$processedPayload .= '&'.$k.'='.$v;
}
$processedPayload = substr($processedPayload, 1);
$computedHash = hash_hmac('sha512', $processedPayload, $this->appStoreSecret);
if($computedHash != $providedHash) {
throw new HandlerException('Hash verification failed', HandlerException::HASH_FAILED);
}
return true;
}
|
{@inheritdoc}
|
public function actionExists($action)
{
if(!in_array($action, $this->eventsMap)){
throw new HandlerException('Action not exists', HandlerException::ACTION_NOT_EXISTS);
}
return true;
}
|
{@inheritdoc}
|
protected function fire($action, $params)
{
if(!isset($this->events[$action])){
throw new HandlerException('Action handler not exists', HandlerException::ACTION_HANDLER_NOT_EXISTS);
}
// prepare params array for handler
// we provide a client library as a param for further requests
$callbackParams = $params;
$callbackParams['client'] = $this->getClient();
$callbackParams = new \ArrayObject($callbackParams, \ArrayObject::STD_PROP_LIST);
// fire handlers for every event
foreach($this->events[$action] as $e){
$result = call_user_func($e, $callbackParams);
if(!$result){
break;
}
}
}
|
fires handlers for a specific action
@param $action
@param $params
@throws HandlerException
|
public function unsubscribe($event, $handler = null)
{
// prevent unsubscribing for non-existing action
$this->actionExists($event);
if($handler===null || empty($this->events)){
$this->events[$event] = array();
}else{
foreach($this->events as &$e){
if($e==$handler){
unset($e);
break;
}
}
}
return true;
}
|
{@inheritdoc}
|
public function subscribe($event, $handler)
{
$this->actionExists($event);
if(!is_callable($handler)){
throw new HandlerException('Incorrect handler specified', HandlerException::INCORRECT_HANDLER_SPECIFIED);
}
if(!isset($this->events[$event])){
$this->events[$event] = array();
}
$this->events[$event][] = $handler;
return count($this->events[$event]);
}
|
{@inheritdoc}
|
public function getClient()
{
if($this->client === null) {
try {
$this->client = Client::factory(
Client::ADAPTER_OAUTH,
array(
'entrypoint' => $this->entrypoint,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
)
);
} catch (ClientException $ex) {
throw new HandlerException('Client initialization failed', HandlerException::CLIENT_INITIALIZATION_FAILED, $ex);
}
}
return $this->client;
}
|
{@inheritdoc}
|
public function refreshTokens()
{
$headers = array(
'Content-Type' => 'application/x-www-form-urlencoded'
);
$headers = $this->injectUserAgent($headers);
$res = $this->getHttpClient()->post($this->entrypoint . '/oauth/token', array(
'client_id' => $this->getClientId(),
'client_secret' => $this->getClientSecret(),
'refresh_token' => $this->getRefreshToken()
), array(
'grant_type'=>'refresh_token'
), $headers);
if(!$res) {
throw new OAuthException('General failure', OAuthException::GENERAL_FAILURE);
} elseif(isset($res['data']['error'])) {
$description = 'General failure';
if(isset($res['data']['error_description'])) {
$description = $res['data']['error_description'];
}
throw new OAuthException(array(
'message' => $description,
'http_error' => $res['data']['error']
), OAuthException::API_ERROR);
}
$this->accessToken = $res['data']['access_token'];
$this->refreshToken = $res['data']['refresh_token'];
$this->expiresIn = (int)$res['data']['expires_in'];
$this->scopes = explode(',', $res['data']['scope']);
return $res['data'];
}
|
Refresh OAuth tokens
@return array
@throws \DreamCommerce\ShopAppstoreLib\Exception\Exception
|
public function run($command)
{
$process = new Process($command);
$process->run();
if (!$process->isSuccessful()) {
throw new \RuntimeException($process->getErrorOutput());
}
return $process->getOutput();
}
|
{@inheritdoc}
|
public function createTempFile($prefix, $content)
{
$filePath = $this->createTempName($prefix);
$this->dumpToFile($filePath, $content);
return $filePath;
}
|
{@inheritdoc}
@throws \Symfony\Component\Filesystem\Exception\IOException If the file cannot be written to.
|
public function redirect_ajax_url( $url, $path, $blog_id ) {
if( strpos( $url, 'admin-ajax' ) ) {
return home_url( "/". $this->keyword ."/" );
}
else {
return $url;
}
}
|
Function that handles rewriting the admin-ajax url to the one we want
|
public function rewrite() {
global $wp_rewrite;
add_rewrite_tag( "%no-admin-ajax%", "([0-9]+)" );
// The whole ajax url matching pattern can be altered with filter "no-admin-ajax/rule"
$default_rule = "^". $this->keyword ."/?$";
$rule = apply_filters( "no-admin-ajax/rule", $default_rule );
add_rewrite_rule(
$rule,
"index.php?no-admin-ajax=true",
"top"
);
}
|
Creates the rewrite
|
public function run_ajax() {
global $wp_query;
if ( $wp_query->get("no-admin-ajax") ) {
// Constant for plugins to know that we are on an AJAX request
define("DOING_AJAX", true);
// If we don't have an action, do nothing
if ( ! isset( $_REQUEST["action"] ) ) {
die(0);
}
// Escape the parameter to prevent disastrous things
$action = esc_attr( $_REQUEST["action"] );
// Run customized no-admin-ajax methods with action "no-admin-ajax/before"
do_action( "no-admin-ajax/before" );
// Run customized no-admin-ajax methods for specific ajax actions with "no-admin-ajax/before/{action}"
do_action( "no-admin-ajax/before/". $action );
// Same headers as WordPress normal AJAX routine sends
$default_headers = array(
"Content-Type: text/html; charset=" . get_option( "blog_charset" ),
"X-Robots-Tag: noindex"
);
// Filter to customize the headers sent by ajax calls
$headers = apply_filters( "no-admin-ajax/headers", $default_headers );
// Send the headers to the user
if ( is_array( $headers ) && count( $headers ) > 0 ) {
foreach ( $headers as $header ) {
@header( $header );
}
}
send_nosniff_header();
nocache_headers();
// Run the actions
if(is_user_logged_in()) {
do_action( "wp_ajax_" . $action );
}
else {
do_action( "wp_ajax_nopriv_" . $action );
}
die(0);
}
}
|
Runs the ajax calls. Equivalent to the real admin-ajax.php
|
public static function setRetryLimit($num){
if($num<1){
throw new HttpException('Limit '.(int)$num.' is too low', HttpException::LIMIT_TOO_LOW);
}
self::$retryLimit = $num;
}
|
*
set connection retrying limit
@param int $num
@throws HttpException
|
public function post($url, $body = array(), $query = array(), $headers = array())
{
return $this->perform('post', $url, $body, $query, $headers);
}
|
{@inheritdoc}
|
public function put($url, $body = array(), $query = array(), $headers = array())
{
return $this->perform('put', $url, $body, $query, $headers);
}
|
{@inheritdoc}
|
public function parseHeaders($src)
{
$headers = array();
foreach ($src as $i) {
$row = explode(':', $i, 2);
// header with no key/value - HTTP response, get code and status
if(!isset($row[1])){
$matches = array();
if(preg_match('#HTTP/[1-2]\.[0-1] ([0-9]{3})(.*)#si', $row[0], $matches)){
$headers['Code'] = $matches[1];
$headers['Status'] = trim($matches[2]);
}
continue;
}
$key = trim($row[0]);
$val = trim($row[1]);
$headers[$key] = $val;
}
return $headers;
}
|
transform headers from $http_response_header
@param array $src
@internal param $headers
@internal param $http_response_header
@return array
|
protected function applyBody(&$contextParams, $methodName, $body, $json = true)
{
// request body
if ($methodName == 'POST' || $methodName == 'PUT') {
$body = (array)$body;
if($json){
$content = @json_encode($body);
if(!$content){
throw new \Exception('Body is not serializable');
}
}else{
$content = http_build_query($body);
}
$contextParams['http']['content'] = $content;
$logger = $this->getLogger();
$logger->debug('Document body: '.var_export($body, true));
$logger->debug('Document body (JSON-ified): '.$content);
}
}
|
add body contents to the POST/PUT request
@param array $contextParams target context resource
@param string $methodName HTTP method
@param array $body request body
@param bool $json body encoding method
|
protected function prepareUrl($url, $query = array())
{
$processedUrl = $url;
if ($query) {
// URL has already query string, merge
if (strpos($url, '?') !== false) {
$components = parse_url($url);
$params = array();
parse_str($components['query'], $params);
$params = $params + $query;
$components['query'] = http_build_query($params);
$processedUrl = http_build_url($components);
} else {
$processedUrl .= '?' . http_build_query($query);
}
}
return $processedUrl;
}
|
return an URL with query string
@param string $url base URL
@param array $query query string contents
@return string
|
protected function doRequest($url, $ctx, &$responseHeaders, $methodName) {
// make a real request
$result = @file_get_contents($url, null, $ctx);
if (!$result) {
throw new \Exception('HTTP request failed', HttpException::REQUEST_FAILED);
}
// catch headers
$responseHeaders = $this->parseHeaders($http_response_header);
foreach (array('Content-Encoding', 'content-encoding') as $header) {
if (isset($responseHeaders[$header])) {
if (strtolower($responseHeaders[$header]) == 'gzip') {
$result = gzinflate(substr($result, 10, -8));
break;
}
}
}
$logger = $this->getLogger();
$logger->debug('Response headers: ' . var_export($responseHeaders, true));
$logger->debug('Response body: ' . $result);
// completely failed
if (!$result && $methodName != 'HEAD') {
throw new \Exception('No response from server');
} else if ($responseHeaders['Code'] < 200 || $responseHeaders['Code'] >= 400) {
// server returned error code
// decode if it's JSON
if ($responseHeaders['Content-Type'] == 'application/json') {
$parsedResult = @json_decode($result, true);
}
// pass responses (not) decoded to the adequate exception parameters
if (isset($parsedResult) && is_array($parsedResult)) {
$description = $parsedResult['error'];
if (isset($parsedResult['error_description'])) {
$description = $parsedResult['error_description'];
}
} else {
$description = 'Server error occurred';
}
throw new HttpException(
$description,
$responseHeaders['Code'],
null,
$methodName,
null,
array(),
array(),
array(),
$result,
$responseHeaders
);
}
return $result;
}
|
perform target request
@param string $url URL
@param Resource $ctx context
@param array $responseHeaders reference to returned headers
@param string $methodName HTTP method
@return mixed|string
@throws \Exception
|
public function getContainerAttributes(Widget $widget): Attributes
{
$attributes = parent::getContainerAttributes($widget);
$attributes->addClass($this->getRowClass());
return $attributes;
}
|
{@inheritDoc}
|
public function getLabelAttributes(Widget $widget): Attributes
{
$attributes = parent::getLabelAttributes($widget);
$attributes->addClass('col-form-label');
$attributes->addClass($this->horizontalConfig['label']);
return $attributes;
}
|
{@inheritDoc}
|
public function getColumnClass(bool $withOffset = false): string
{
$class = (string) $this->horizontalConfig['control'];
if ($withOffset) {
$class .= ' ' . $this->horizontalConfig['offset'];
}
return $class;
}
|
Get the column class.
@param bool $withOffset If true the offset class is added.
@return string
|
public function request(Resource $res, $method, $objectPath = null, $data = array(), $query = array())
{
$this->authenticate();
$client = $this->getHttpClient();
if(!method_exists($client, $method)) {
throw new Exception('Method not supported', Exception::METHOD_NOT_SUPPORTED);
}
$client->setSkipSsl($this->skipSsl);
$url = $this->entrypoint.'/'.$res->getName();
if($objectPath){
if(is_array($objectPath)){
$objectPath = join('/', $objectPath);
}
$url .= '/'.$objectPath;
}
$headers = array(
'Authorization' => 'Bearer ' . $this->getAccessToken(),
'Content-Type' => 'application/json',
'Accept-Language' => $this->getLocale() . ';q=0.8'
);
$headers = $this->injectUserAgent($headers);
try {
// dispatch correct method
if(in_array($method, array('get', 'delete', 'head'))){
return call_user_func(array(
$client, $method
), $url, $query, $headers);
} else {
return call_user_func(array(
$client, $method
), $url, $data, $query, $headers);
}
} catch(HttpException $ex) {
// fire a handler for token reneval
$previous = $ex->getPrevious();
if($previous instanceof HttpException){
$response = $previous->getResponse();
$handler = $this->onTokenInvalidHandler;
if($response['error']=='unauthorized_client' && $handler){
$exceptionHandled = $handler($this, $ex);
if($exceptionHandled){
return array();
}
}
}
throw new Exception('HTTP error: '.$ex->getMessage(), Exception::API_ERROR, $ex);
}
}
|
{@inheritdoc}
|
public function getHttpClient()
{
if($this->httpClient === null) {
$this->httpClient = Http::instance();
if($this->logger){
$this->httpClient->setLogger($this->logger);
}
}
$this->httpClient->setSkipSsl($this->skipSsl);
return $this->httpClient;
}
|
{@inheritdoc}
|
public function init()
{
parent::init();
self::$plugin = $this;
$user = Craft::$app->getUser();
$request = Craft::$app->getRequest();
if (!$user->getIsAdmin() || !$request->getIsCpRequest() || $request->getIsConsoleRequest()) {
return;
}
// Handler: EVENT_AFTER_LOAD_PLUGINS
Event::on(
Plugins::class,
Plugins::EVENT_AFTER_LOAD_PLUGINS,
function () {
$this->doIt();
}
);
/**
* Logging in Craft involves using one of the following methods:
*
* Craft::trace(): record a message to trace how a piece of code runs. This is mainly for development use.
* Craft::info(): record a message that conveys some useful information.
* Craft::warning(): record a warning message that indicates something unexpected has happened.
* Craft::error(): record a fatal error that should be investigated as soon as possible.
*
* Unless `devMode` is on, only Craft::warning() & Craft::error() will log to `craft/storage/logs/web.log`
*
* It's recommended that you pass in the magic constant `__METHOD__` as the second parameter, which sets
* the category to the method (prefixed with the fully qualified class name) where the constant appears.
*
* To enable the Yii debug toolbar, go to your user account in the AdminCP and check the
* [] Show the debug toolbar on the front end & [] Show the debug toolbar on the Control Panel
*
* http://www.yiiframework.com/doc-2.0/guide-runtime-logging.html
*/
Craft::info(
Craft::t(
'cp-field-inspect',
'{name} plugin loaded',
['name' => $this->name]
),
__METHOD__
);
}
|
Set our $plugin static property to this class so that it can be accessed via
CpFieldInspect::$plugin
Called after the plugin class is instantiated; do any one-time initialization
here such as hooks and events.
If you have a '/vendor/autoload.php' file, it will be loaded for you automatically;
you do not need to load it in your init() method.
|
protected function doIt()
{
$request = Craft::$app->getRequest();
if ($request->getIsAjax()) {
if (!$request->getIsPost()) {
return false;
}
$segments = $request->segments;
$actionSegment = $segments[count($segments) - 1];
if ($actionSegment !== 'get-editor-html') {
return false;
}
Craft::$app->getView()->registerJs('Craft.CpFieldInspectPlugin.initElementEditor();');
} else {
$data = array(
'redirectUrl' => Craft::$app->getSecurity()->hashData(implode('/', $request->segments)),
'fields' => array(),
'entryTypeIds' => array(),
'baseEditFieldUrl' => rtrim(UrlHelper::cpUrl('settings/fields/edit'), '/'),
'baseEditEntryTypeUrl' => rtrim(UrlHelper::cpUrl('settings/sections/sectionId/entrytypes'), '/'),
'baseEditGlobalSetUrl' => rtrim(UrlHelper::cpUrl('settings/globals'), '/'),
'baseEditCategoryGroupUrl' => rtrim(UrlHelper::cpUrl('settings/categories'), '/'),
'baseEditCommerceProductTypeUrl' => rtrim(UrlHelper::cpUrl('commerce/settings/producttypes'), '/'),
);
$sectionIds = Craft::$app->getSections()->getAllSectionIds();
foreach ($sectionIds as $sectionId)
{
$entryTypes = Craft::$app->getSections()->getEntryTypesBySectionId($sectionId);
$data['entryTypeIds']['' . $sectionId] = array();
foreach ($entryTypes as $entryType)
{
$data['entryTypeIds']['' . $sectionId][] = $entryType->id;
}
}
$fields = Craft::$app->getFields()->getAllFields();
foreach ($fields as $field)
{
$data['fields'][$field->handle] = array(
'id' => $field->id,
'handle' => $field->handle,
);
}
Craft::$app->getView()->registerAssetBundle(CpFieldInspectBundle::class);
Craft::$app->getView()->registerJs('Craft.CpFieldInspectPlugin.init('.json_encode($data).');');
}
}
|
=========================================================================
|
public function create(string $type, array $config): FormLayout
{
$config = array_merge(['widgets' => []], $config);
$widgetConfig = $this->buildWidgetConfig($type, $config);
$fallbackConfig = $this->buildFallbackConfig($type, $config);
switch ($type) {
case 'bs_horizontal':
return new HorizontalFormLayout(
$widgetConfig,
$fallbackConfig,
$this->buildHorizontalConfig($config)
);
default:
return new DefaultFormLayout($widgetConfig, $fallbackConfig);
}
}
|
{@inheritdoc}
|
private function buildWidgetConfig(string $type, array $config): array
{
$type = substr($type, 3);
$configKey = 'form.layouts.' . $type . '.widgets';
$bootstrapConfig = $this->environment->getConfig();
$widgetConfig = ArrayUtil::merge($this->widgetConfig, $bootstrapConfig->get('form.widgets'));
if ($bootstrapConfig->has($configKey)) {
$widgetConfig = ArrayUtil::merge($widgetConfig, $bootstrapConfig->get($configKey));
}
foreach (StringUtil::deserialize($config['widgets'], true) as $widget) {
if ($widget['widget'] === '') {
continue;
}
foreach ($this->sections as $section) {
if ($widget[$section]) {
$widgetConfig[$widget['widget']]['templates'][$section] = $widget[$section];
}
}
}
return $widgetConfig;
}
|
Build the widget config.
@param string $type Widget type.
@param array $config Configuration.
@return array
|
private function buildFallbackConfig(string $type, array $config): array
{
$type = substr($type, 3);
$fallbackConfig = $this->environment->getConfig()->get('form.layouts.' . $type, []);
$fallbackConfig = ArrayUtil::merge($this->fallbackConfig, $fallbackConfig);
foreach ($this->sections as $section) {
$name = 'fallback' . ucfirst($section);
if ($config[$name]) {
$fallbackConfig['templates'][$section] = $config[$name];
}
}
return $fallbackConfig;
}
|
Build the fallback config.
@param string $type Layout type.
@param array $config Configuration.
@return array
|
private function buildHorizontalConfig(array $config): array
{
$horizontalConfig = $this->environment->getConfig()->get('form.layouts.horizontal.classes', []);
foreach (['row', 'label', 'control', 'offset'] as $key) {
if (!empty($config['bs_' . $key])) {
$horizontalConfig[$key] = $config['bs_' . $key];
}
}
return $horizontalConfig;
}
|
Build horizontal config.
@param array $config Horizontal config.
@return array
|
public function reset()
{
$this->filters = array();
$this->limit = null;
$this->order = null;
$this->page = null;
return $this;
}
|
reset filters object state
|
protected function getCriteria()
{
$result = array();
if($this->filters){
$result['filters'] = $this->filters;
}
if($this->limit!==null){
$result['limit'] = $this->limit;
}
if($this->order!==null){
$result['order'] = $this->order;
}
if($this->page!==null){
$result['page'] = $this->page;
}
return $result;
}
|
get an array with specified criteria
@return array
|
public function limit($count)
{
if($count<1 || $count>50){
throw new \RuntimeException('Limit beyond 1-50 range', ResourceException::LIMIT_BEYOND_RANGE);
}
$this->limit = $count;
return $this;
}
|
set records limit
@param int $count collection's items limit in range 1-50
@return $this
@throws \RuntimeException
|
public function filters($filters)
{
if(!is_array($filters)){
throw new \RuntimeException('Filters not specified', ResourceException::FILTERS_NOT_SPECIFIED);
}
$this->filters = json_encode($filters);
return $this;
}
|
set filters for finding
@param array $filters
@return $this
@throws \RuntimeException
|
public function page($page)
{
$page = (int)$page;
if($page<0){
throw new \RuntimeException('Invalid page specified', ResourceException::INVALID_PAGE);
}
$this->page = $page;
return $this;
}
|
specify page
@param int $page
@return $this
@throws \RuntimeException
|
public function order($expr)
{
$matches = array();
$expr = (array)$expr;
$result = array();
foreach($expr as $e) {
// basic syntax, with asc/desc suffix
if (preg_match('/([a-z_0-9.]+) (asc|desc)$/i', $e)) {
$result[] = $e;
} else if (preg_match('/([\+\-]?)([a-z_0-9.]+)/i', $e, $matches)) {
// alternative syntax - with +/- prefix
$subResult = $matches[2];
if ($matches[1] == '' || $matches[1] == '+') {
$subResult .= ' asc';
} else {
$subResult .= ' desc';
}
$result[] = $subResult;
} else {
// something which should never happen but take care [;
throw new \RuntimeException('Cannot understand ordering expression', ResourceException::ORDER_NOT_SUPPORTED);
}
}
$this->order = $result;
}
|
order record by column
@param string $expr syntax:
<field> (asc|desc)
or
(+|-)<field>
@return $this
@throws \RuntimeException
|
public function get()
{
$query = $this->getCriteria();
$args = func_get_args();
if(empty($args)){
$args = null;
}
$isCollection = $this->isCollection($args);
$response = '';
try {
$response = $this->client->request($this, 'get', $args, array(), $query);
} catch(Exception $ex) {
$this->dispatchException($ex);
}
return $this->transformResponse($response, $isCollection);
}
|
Read Resource
@param mixed $args,... params
@return \ArrayObject
@throws ResourceException
|
public function head()
{
$query = $this->getCriteria();
$args = func_get_args();
if(empty($args)){
$args = null;
}
$response = '';
try {
$response = $this->client->request($this, 'head', $args, array(), $query);
} catch(Exception $ex) {
$this->dispatchException($ex);
}
return $this->transformResponse($response, true);
}
|
Read Resource without data
@return \ArrayObject
@throws ResourceException
|
public function post($data)
{
$args = func_get_args();
if(count($args) == 1) {
$args = null;
} else {
$data = array_pop($args);
}
$response = '';
try {
$response = $this->client->request($this, 'post', $args, $data);
return $response['data'];
} catch (Exception $ex) {
$this->dispatchException($ex);
}
}
|
Create Resource
@param array $data
@return integer
@throws ResourceException
|
public function put($id = null, $data = array())
{
$args = func_get_args();
if(count($args) == 2){
$args = $id;
}else{
$data = array_pop($args);
}
try {
$this->client->request($this, 'put', $args, $data);
} catch(Exception $ex) {
$this->dispatchException($ex);
}
return true;
}
|
Update Resource
@param null|int $id
@param array $data
@return bool
@throws ResourceException
|
public function delete($id = null)
{
if($this->getCriteria()){
throw new ResourceException('Filtering not supported in DELETE', ResourceException::FILTERS_IN_UNSUPPORTED_METHOD);
}
$args = func_get_args();
if(count($args) == 1){
$args = $id;
}
try {
$this->client->request($this, 'delete', $args);
}catch(Exception $ex){
$this->dispatchException($ex);
}
return true;
}
|
Delete Resource
@param int $id
@return bool
@throws ResourceException
|
public static function forWidget(Widget $widget): self
{
$values = StringUtil::deserialize($widget->bs_inputGroup, true);
$helper = new static();
foreach ($values as $entry) {
if (!strlen($entry['addon'])) {
continue;
}
if ($entry['position'] === 'after') {
$helper->addAfter($entry['addon']);
} else {
$helper->addBefore($entry['addon']);
}
}
return $helper;
}
|
Create input group helper for a widget.
@param Widget $widget Form widget.
@return static
|
public function addAfter(string $content, bool $text = true): self
{
$this->after[] = [
'content' => $content,
'text' => $text
];
return $this;
}
|
Add after entry.
@param string $content Content of the add on.
@param bool $text If true, no input-group-text wrapper is added.
@return $this
|
public function addBefore(string $content, bool $text = true): self
{
$this->before[] = [
'content' => $content,
'text' => $text
];
return $this;
}
|
Add before entry.
@param string $content Content of the addo n.
@param bool $text If true, no input-group-text wrapper is added.
@return $this
|
public function createTempFile($prefix, $content)
{
$filePath = $this->createTempName($prefix);
file_put_contents($filePath, $content);
return $filePath;
}
|
{@inheritdoc}
|
public function adjustPalettes(): void
{
// Load custom form config.
$this->environment->enterContext(FormContext::forForm((int) CURRENT_ID));
$widgets = $this->environment->getConfig()->get('form.widgets', []);
foreach ($widgets as $name => $config) {
if (!empty($config['input_group'])) {
try {
MetaPalettes::appendFields('tl_form_field', $name, 'fconfig', ['bs_addInputGroup']);
// @codingStandardsIgnoreStart Catch statement is empty on purpose
} catch (PaletteNotFoundException | LegacyPaletteNotFoundException $e) {
// Palette does not exist. Just skip it.
}
// @codingStandardsIgnoreEnd
}
}
}
|
Adjust the palettes.
@return void
|
public function job($command)
{
$line = new Job($command, $this);
$this->lines[] = $line;
return $line;
}
|
@param string $command
@return Job
|
public function onGetPageLayout(PageModel $pageModel, LayoutModel $layoutModel): void
{
if ($this->manager->hasDefaultThemeLayout()) {
return;
}
$this->manager->setDefaultThemeLayout($this->factory->create('bs_default', []));
}
|
Create default bootstrap form layout.
@param PageModel $pageModel Page model.
@param LayoutModel $layoutModel Layout model.
@return void
@SuppressWarnings(PHPMD.UnusedFormalParameter)
|
public function updateWith(Cron $cron, $key)
{
$this->cronManipulator->replace($this->updateContent($cron, $key));
}
|
@param Cron $cron
@param $key
@throws \Exception
|
public function authenticate($force = false)
{
if($this->accessToken !== null && !$force) {
return false;
}
$headers = array(
'Accept-Language' => $this->getLocale() . ';q=0.8',
'Content-Type' => 'application/x-www-form-urlencoded'
);
$headers = $this->injectUserAgent($headers);
$res = $this->getHttpClient()->post(
$this->entrypoint . '/auth',
array(),
array(
'client_id' => $this->username,
'client_secret' => $this->password
),
$headers
);
if(!$res) {
throw new BasicAuthException('General failure', BasicAuthException::GENERAL_FAILURE);
} elseif(isset($res['data']['error'])) {
$description = 'General failure';
if(isset($res['data']['error_description'])) {
$description = $res['data']['error_description'];
}
throw new BasicAuthException(array(
'message' => $description,
'http_error' => $res['data']['error']
), BasicAuthException::API_ERROR);
}
// automatically set token to the freshly requested
$this->setAccessToken($res['data']['access_token']);
return $res['data'];
}
|
{@inheritdoc}
|
public function get()
{
$query = $this->getCriteria();
$args = func_get_args();
if(empty($args)){
$args = array("system");
}
$isCollection = !$this->isSingleOnly && count($args)==1;
try {
$response = $this->client->request($this, 'get', $args, array(), $query);
} catch(ClientException $ex) {
throw new Resource\Exception\CommunicationException($ex->getMessage(), $ex);
}
return $this->transformResponse($response, $isCollection);
}
|
Read Resource
@param mixed $args,... params
@return \ArrayObject
@throws ResourceException
|
public function onKernelRequest(GetResponseEvent $event): void
{
$request = $event->getRequest();
if (!$event->isMasterRequest()) {
return;
}
if ($request->attributes->get(SetIsApiRequestListener::API_FLAG_NAME) !== true) {
return;
}
if (!$this->isDecodeable($request)) {
return;
}
try {
$data = $this->decoder->decode((string) $request->getContent(), 'json');
} catch (UnexpectedValueException $e) {
throw new BadRequestHttpException('Request body has an invalid format', $e);
}
if (!is_array($data)) {
throw new BadRequestHttpException('Request body has an invalid format');
}
$request->attributes->set('data', new ParameterBag($data));
}
|
Decodes the request data into request parameter bag.
|
private function isDecodeable(Request $request): bool
{
if (
!in_array(
$request->getMethod(),
[Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_PATCH, Request::METHOD_DELETE],
true
)
) {
return false;
}
return $request->getContentType() === 'json';
}
|
Check if we should try to decode the body.
|
protected function addViewTypeForm(FormBuilderInterface $builder, array $options): void
{
/** @var \Netgen\BlockManager\Block\BlockDefinitionInterface $blockDefinition */
$blockDefinition = $options['block']->getDefinition();
$this->processViewTypeConfig($blockDefinition);
$builder->add(
'view_type',
ChoiceType::class,
[
'label' => 'block.view_type',
'choices' => array_flip($this->viewTypes),
'property_path' => 'viewType',
] + $this->getChoicesAsValuesOption()
);
$builder->add(
'item_view_type',
ChoiceType::class,
[
'label' => 'block.item_view_type',
'choices' => array_flip(call_user_func_array('array_merge', $this->itemViewTypes)),
'choice_attr' => function ($value): array {
return [
'data-master' => implode(',', $this->viewTypesByItemViewType[$value]),
];
},
'property_path' => 'itemViewType',
] + $this->getChoicesAsValuesOption()
);
}
|
Adds view type and item view type forms to the provided form builder.
|
protected function addParametersForm(FormBuilderInterface $builder, array $options, array $groups = []): void
{
/** @var \Netgen\BlockManager\Block\BlockDefinitionInterface $blockDefinition */
$blockDefinition = $options['block']->getDefinition();
$builder->add(
'parameters',
ParametersType::class,
[
'label' => false,
'inherit_data' => true,
'property_path' => 'parameterValues',
'parameter_definitions' => $blockDefinition,
'label_prefix' => 'block.' . $blockDefinition->getIdentifier(),
'groups' => $groups,
]
);
}
|
Adds the parameters form to the provided builder.
|
private function processViewTypeConfig(BlockDefinitionInterface $blockDefinition): void
{
$blockDefinitionParameters = array_keys($blockDefinition->getParameterDefinitions());
foreach ($blockDefinition->getViewTypes() as $viewType) {
$this->viewTypes[$viewType->getIdentifier()] = $viewType->getName();
foreach ($viewType->getItemViewTypes() as $itemViewType) {
$this->itemViewTypes[$viewType->getIdentifier()][$itemViewType->getIdentifier()] = $itemViewType->getName();
$this->viewTypesByItemViewType[$itemViewType->getIdentifier()][] = $viewType->getIdentifier();
}
$includedParameters = [];
$excludedParameters = [];
$validParameters = $viewType->getValidParameters();
if (!is_array($validParameters)) {
$includedParameters = $blockDefinitionParameters;
} elseif (count($validParameters) > 0) {
foreach ($validParameters as $validParameter) {
mb_strpos($validParameter, '!') === 0 ?
$excludedParameters[] = mb_substr($validParameter, 1) :
$includedParameters[] = $validParameter;
if (count($includedParameters) === 0) {
$includedParameters = $blockDefinitionParameters;
}
}
}
foreach ($includedParameters as $includedParameter) {
if (!in_array($includedParameter, $excludedParameters, true)) {
$this->viewTypesByParameters[$includedParameter][] = $viewType->getIdentifier();
}
}
}
}
|
Generates the list of valid view types for every item view type
and for every parameter, according to config provided by the block definition.
These lists are used by the interface to hide and show item view types
and parameters based on selected view type.
@todo Move this code somewhere else
|
public function onKernelResponse(FilterResponseEvent $event): void
{
if (!$event->isMasterRequest()) {
return;
}
$blockView = $event->getRequest()->attributes->get('ngbmView');
if (!$blockView instanceof BlockViewInterface) {
return;
}
$this->tagger->tagBlock($event->getResponse(), $blockView->getBlock());
}
|
Tags the response with the data for block provided by the event.
|
public function mapConfig(array $config, array $configDefinitions): Generator
{
foreach ($configDefinitions as $configKey => $configDefinition) {
yield $configKey => Config::fromArray(
[
'configKey' => $configKey,
'definition' => $configDefinition,
'parameters' => iterator_to_array(
$this->parameterMapper->mapParameters(
$configDefinition,
$config[$configKey] ?? []
)
),
]
);
}
}
|
Maps the provided config array to API values according to provided config definitions.
@param array<string, array<string, mixed>> $config
@param \Netgen\BlockManager\Config\ConfigDefinitionInterface[] $configDefinitions
@return \Generator
|
public function serializeValues(array $configStructs, array $configDefinitions, array $fallbackValues = []): Generator
{
foreach ($configDefinitions as $configKey => $configDefinition) {
$configValues = [];
if (
isset($configStructs[$configKey]) &&
$configStructs[$configKey] instanceof ParameterStruct
) {
$configValues = $configStructs[$configKey]->getParameterValues();
}
yield $configKey => iterator_to_array(
$this->parameterMapper->serializeValues(
$configDefinition,
$configValues,
$fallbackValues[$configKey] ?? []
)
);
}
}
|
Serializes the existing config struct values based on provided config definitions.
@param \Netgen\BlockManager\API\Values\ParameterStruct[] $configStructs
@param \Netgen\BlockManager\Config\ConfigDefinitionInterface[] $configDefinitions
@param array<string, array<string, mixed>> $fallbackValues
@return \Generator
|
public function onKernelRequest(GetResponseEvent $event): void
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
$currentRoute = $request->attributes->get('_route', '');
if (mb_stripos($currentRoute, self::ADMIN_ROUTE_PREFIX) !== 0) {
return;
}
$request->attributes->set(self::ADMIN_FLAG_NAME, true);
$adminEvent = new AdminMatchEvent($event->getRequest(), $event->getRequestType());
$this->eventDispatcher->dispatch($adminEvent, BlockManagerAdminEvents::ADMIN_MATCH);
}
|
Sets the self::ADMIN_FLAG_NAME flag if this is a request in admin interface.
|
public function createPosition(array $conditions, ?int $position = null, ?int $endPosition = null, bool $allowOutOfRange = false): int
{
$nextPosition = $this->getNextPosition($conditions);
if ($position === null) {
return $nextPosition;
}
if ($position < 0) {
throw new BadStateException('position', 'Position cannot be negative.');
}
if (!$allowOutOfRange && $position > $nextPosition) {
throw new BadStateException('position', 'Position is out of range.');
}
if ($endPosition !== null && $endPosition < $position) {
throw new BadStateException('position', 'When creating a position, end position needs to be greater or equal than start position.');
}
$this->incrementPositions(
$conditions,
$position,
$endPosition
);
return $position;
}
|
Processes the database table to create space for an item which will
be inserted at specified position.
@throws \Netgen\BlockManager\Exception\BadStateException If position is out of range
|
public function moveToPosition(array $conditions, int $originalPosition, int $position, bool $allowOutOfRange = false): int
{
$nextPosition = $this->getNextPosition($conditions);
if ($position < 0) {
throw new BadStateException('position', 'Position cannot be negative.');
}
if (!$allowOutOfRange && $position >= $nextPosition) {
throw new BadStateException('position', 'Position is out of range.');
}
if ($position > $originalPosition) {
$this->decrementPositions(
$conditions,
$originalPosition + 1,
$position
);
} elseif ($position < $originalPosition) {
$this->incrementPositions(
$conditions,
$position,
$originalPosition - 1
);
}
return $position;
}
|
Processes the database table to make space for the item which
will be moved inside the table.
@throws \Netgen\BlockManager\Exception\BadStateException If position is out of range
|
public function getNextPosition(array $conditions): int
{
$columnName = $conditions['column'];
$query = $this->connection->createQueryBuilder();
$query->select($this->connection->getDatabasePlatform()->getMaxExpression($columnName) . ' AS ' . $columnName)
->from($conditions['table']);
$this->applyConditions($query, $conditions['conditions']);
$data = $query->execute()->fetchAll(PDO::FETCH_ASSOC);
return (int) ($data[0][$columnName] ?? -1) + 1;
}
|
Returns the next available position in the table.
|
private function incrementPositions(array $conditions, ?int $startPosition = null, ?int $endPosition = null): void
{
$columnName = $conditions['column'];
$query = $this->connection->createQueryBuilder();
$query
->update($conditions['table'])
->set($columnName, $columnName . ' + 1');
if ($startPosition !== null) {
$query->andWhere($query->expr()->gte($columnName, ':start_position'));
$query->setParameter('start_position', $startPosition, Type::INTEGER);
}
if ($endPosition !== null) {
$query->andWhere($query->expr()->lte($columnName, ':end_position'));
$query->setParameter('end_position', $endPosition, Type::INTEGER);
}
$this->applyConditions($query, $conditions['conditions']);
$query->execute();
}
|
Increments all positions in a table starting from provided position.
|
private function applyConditions(QueryBuilder $query, array $conditions): void
{
foreach ($conditions as $identifier => $value) {
$query->andWhere(
$query->expr()->eq($identifier, ':' . $identifier)
);
$query->setParameter($identifier, $value, is_int($value) ? Type::INTEGER : Type::STRING);
}
}
|
Applies the provided conditions to the query.
|
protected function buildView(
$value,
string $context = ViewInterface::CONTEXT_DEFAULT,
array $parameters = [],
?Response $response = null
): ViewInterface {
/** @var \Netgen\BlockManager\View\ViewBuilderInterface $viewBuilder */
$viewBuilder = $this->get('netgen_block_manager.view.view_builder');
$view = $viewBuilder->buildView($value, $context, $parameters);
$view->setResponse($response instanceof Response ? $response : new Response());
return $view;
}
|
Builds the view from provided value.
@param mixed $value
@param string $context
@param array<string, mixed> $parameters
@param \Symfony\Component\HttpFoundation\Response $response
@return \Netgen\BlockManager\View\ViewInterface
|
private function buildLayoutTypes(ContainerBuilder $container, array $layoutTypes): Generator
{
foreach ($layoutTypes as $identifier => $layoutType) {
$serviceIdentifier = sprintf('netgen_block_manager.layout.layout_type.%s', $identifier);
$container->register($serviceIdentifier, LayoutType::class)
->setArguments([$identifier, $layoutType])
->setLazy(true)
->setPublic(true)
->setFactory([LayoutTypeFactory::class, 'buildLayoutType']);
yield $identifier => new Reference($serviceIdentifier);
}
}
|
Builds the layout type objects from provided configuration.
|
private function validateLayoutTypes(array $layoutTypes, array $blockDefinitions): void
{
foreach ($layoutTypes as $layoutType => $layoutTypeConfig) {
foreach ($layoutTypeConfig['zones'] as $zoneConfig) {
foreach ($zoneConfig['allowed_block_definitions'] as $blockDefinition) {
if (!isset($blockDefinitions[$blockDefinition])) {
throw new RuntimeException(
sprintf(
'Block definition "%s" used in "%s" layout type does not exist.',
$blockDefinition,
$layoutType
)
);
}
}
}
}
}
|
Validates layout type config.
@throws \Netgen\BlockManager\Exception\RuntimeException If validation failed
|
public function getItemPath($value, ?string $valueType = null): string
{
try {
$item = null;
if (is_string($value) && $valueType === null) {
$itemUri = parse_url($value);
if (!is_array($itemUri) || ($itemUri['scheme'] ?? '') === '' || !isset($itemUri['host'])) {
throw ItemException::invalidValue($value);
}
$item = $this->cmsItemLoader->load(
$itemUri['host'],
str_replace('-', '_', $itemUri['scheme'])
);
} elseif ((is_int($value) || is_string($value)) && is_string($valueType)) {
$item = $this->cmsItemLoader->load($value, $valueType);
} elseif ($value instanceof CmsItemInterface) {
$item = $value;
}
if (!$item instanceof CmsItemInterface) {
throw ItemException::canNotLoadItem();
}
return $this->urlGenerator->generate($item);
} catch (Throwable $t) {
$this->errorHandler->handleError($t);
}
return '';
}
|
The method returns the full path of provided item.
It accepts three kinds of references to the item:
1) URI with value_type://value format, e.g. type://42
2) ID and value type as separate arguments
3) \Netgen\BlockManager\Item\CmsItemInterface object
@param mixed $value
@param string|null $valueType
@throws \Netgen\BlockManager\Exception\Item\ItemException If provided item or item reference is not valid
@return string
|
public function mapCollections(array $data): array
{
$collections = [];
foreach ($data as $dataItem) {
$collectionId = (int) $dataItem['id'];
$locale = $dataItem['locale'];
if (!isset($collections[$collectionId])) {
$collections[$collectionId] = [
'id' => $collectionId,
'status' => (int) $dataItem['status'],
'offset' => (int) $dataItem['start'],
'limit' => $dataItem['length'] !== null ? (int) $dataItem['length'] : null,
'isTranslatable' => (bool) $dataItem['translatable'],
'mainLocale' => $dataItem['main_locale'],
'alwaysAvailable' => (bool) $dataItem['always_available'],
];
}
$collections[$collectionId]['availableLocales'][] = $locale;
}
return array_values(
array_map(
static function (array $collectionData): Collection {
sort($collectionData['availableLocales']);
return Collection::fromArray($collectionData);
},
$collections
)
);
}
|
Maps data from database to collection values.
@return \Netgen\BlockManager\Persistence\Values\Collection\Collection[]
|
public function mapItems(array $data): array
{
$items = [];
foreach ($data as $dataItem) {
$items[] = Item::fromArray(
[
'id' => (int) $dataItem['id'],
'collectionId' => (int) $dataItem['collection_id'],
'position' => (int) $dataItem['position'],
'value' => $dataItem['value'],
'valueType' => $dataItem['value_type'],
'status' => (int) $dataItem['status'],
'config' => $this->buildParameters((string) $dataItem['config']),
]
);
}
return $items;
}
|
Maps data from database to item values.
@return \Netgen\BlockManager\Persistence\Values\Collection\Item[]
|
public function mapQueries(array $data): array
{
$queries = [];
foreach ($data as $dataItem) {
$queryId = (int) $dataItem['id'];
$locale = $dataItem['locale'];
if (!isset($queries[$queryId])) {
$queries[$queryId] = [
'id' => $queryId,
'collectionId' => (int) $dataItem['collection_id'],
'type' => $dataItem['type'],
'status' => (int) $dataItem['status'],
];
}
$queries[$queryId]['parameters'][$locale] = $this->buildParameters((string) $dataItem['parameters']);
$queries[$queryId]['availableLocales'][] = $locale;
}
$queries = array_values(
array_map(
static function (array $queryData): Query {
ksort($queryData['parameters']);
sort($queryData['availableLocales']);
return Query::fromArray($queryData);
},
$queries
)
);
return $queries;
}
|
Maps data from database to query values.
|
private function buildParameters(string $parameters): array
{
$decodedParameters = json_decode($parameters, true);
return is_array($decodedParameters) ? $decodedParameters : [];
}
|
Builds the array of parameters from provided JSON string.
|
private function validatePriorities(Request $request): void
{
$this->validate(
$request->request->get('rule_ids'),
[
new Constraints\NotBlank(),
new Constraints\Type(['type' => 'array']),
new Constraints\All(
[
'constraints' => [
new Constraints\NotBlank(),
new Constraints\Type(['type' => 'scalar']),
],
]
),
],
'rule_ids'
);
}
|
Validates list of rules from the request when updating priorities.
@throws \Netgen\BlockManager\Exception\Validation\ValidationException If validation failed
|
public function collectLayout(LayoutViewInterface $layoutView): void
{
$layout = $layoutView->getLayout();
$this->data['layout'] = [
'id' => $layout->getId(),
'name' => $layout->getName(),
'type' => $layout->getLayoutType()->getName(),
'context' => $layoutView->getContext(),
'template' => null,
'template_path' => null,
];
if ($layoutView->getTemplate() !== null) {
$templateSource = $this->getTemplateSource($layoutView->getTemplate());
$this->data['layout']['template'] = $templateSource->getName();
$this->data['layout']['template_path'] = $templateSource->getPath();
}
}
|
Collects the layout data.
|
public function collectRule(Rule $rule): void
{
$this->data['rule'] = [
'id' => $rule->getId(),
];
foreach ($rule->getTargets() as $target) {
$this->data['rule']['targets'][] = [
'type' => $target->getTargetType()::getType(),
'value' => $this->formatVar($target->getValue()),
];
}
foreach ($rule->getConditions() as $condition) {
$this->data['rule']['conditions'][] = [
'type' => $condition->getConditionType()::getType(),
'value' => $this->formatVar($condition->getValue()),
];
}
}
|
Collects the rule data.
|
public function collectBlockView(BlockViewInterface $blockView): void
{
$block = $blockView->getBlock();
$blockDefinition = $block->getDefinition();
$blockData = [
'id' => $block->getId(),
'layout_id' => $block->getLayoutId(),
'definition' => $blockDefinition->getName(),
'view_type' => $blockDefinition->hasViewType($block->getViewType()) ?
$blockDefinition->getViewType($block->getViewType())->getName() :
'Invalid view type',
'locale' => $block->getLocale(),
'template' => null,
'template_path' => null,
];
if ($blockView->getTemplate() !== null) {
$templateSource = $this->getTemplateSource($blockView->getTemplate());
$blockData['template'] = $templateSource->getName();
$blockData['template_path'] = $templateSource->getPath();
}
$this->data['blocks'][] = $blockData;
}
|
Collects the block view data.
|
public function onView(GetResponseForControllerResultEvent $event): void
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
$value = $event->getControllerResult();
if (!$value instanceof AbstractValue) {
return;
}
$context = [];
if ($request->query->get('html') === 'false') {
$context['disable_html'] = true;
}
$response = new JsonResponse(null, $value->getStatusCode());
$response->setContent(
$this->serializer->serialize($value, 'json', $context)
);
$event->setResponse($response);
}
|
Serializes the value provided by the event.
|
private function buildParameterDefinition(ParameterBuilderInterface $builder): ParameterDefinition
{
$data = [
'name' => $builder->getName(),
'type' => $builder->getType(),
'options' => $builder->getOptions(),
'isRequired' => $builder->isRequired(),
'defaultValue' => $builder->getDefaultValue(),
'label' => $builder->getLabel(),
'groups' => $builder->getGroups(),
'constraints' => $builder->getConstraints(),
];
// We build the sub parameters in order to lock the child builders
$subParameters = $builder->buildParameterDefinitions();
if (!$builder->getType() instanceof CompoundParameterTypeInterface) {
return ParameterDefinition::fromArray($data);
}
$data['parameterDefinitions'] = $subParameters;
return CompoundParameterDefinition::fromArray($data);
}
|
Builds the parameter definition.
|
private function validateConstraints(array $constraints): bool
{
foreach ($constraints as $constraint) {
if (!$constraint instanceof Closure && !$constraint instanceof Constraint) {
return false;
}
}
return true;
}
|
Validates the list of constraints to be either a Symfony constraint or a closure.
|
public function extract($object): array
{
if (!is_object($object)) {
throw new RuntimeException(
sprintf('%s expects the provided $object to be a PHP object', __METHOD__)
);
}
return (function (): array {
return get_object_vars($this);
})->call($object);
}
|
Extract values from an object.
@param object $object
@return array<string, mixed>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.