sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function parseControlWord(Token\Control\Word $token, Element\Group $group)
{
// if a class exists for the control word
$filename = ucfirst($token->getWord());
$classname = "Jstewmc\\Rtf\\Element\\Control\\Word\\$filename";
if (class_exists($classname)) {
// instantiate the control word element and break
$word = new $classname();
} else {
// otherwise, instantiate a generic control word
$word = new Element\Control\Word\Word();
$word->setWord($token->getWord());
}
// set the element's parameter
$word->setParameter($token->getParameter());
$word->setIsSpaceDelimited($token->getIsSpaceDelimited());
// append the element
$word->setParent($group);
$group->appendChild($word);
return;
}
|
Parses a control word token
@param Jstewmc\Rtf\Token\Control\Word $token the control word token
@param Jstewmc\Rtf\Element\Group $group the current group
@return void
@since 0.1.0
|
entailment
|
protected function parseGroupOpen(Token\Group\Open $token, \SplStack $stack)
{
$group = new Element\Group();
// if the group is not the root
if ($stack->count() > 0) {
// set the parent-child and child-parent relationships
$group->setParent($stack->top());
$stack->top()->appendChild($group);
}
$stack->push($group);
return;
}
|
Parses a group-open token
@param Jstewmc\Rtf\Token\Group\Open $token the group-open token
@param SplStack $stack the group stack
@param Jstewmc\Rtf\Element\Group $root the root group (optional; if
omitted, defaults to null)
@return void
@since 0.1.0
|
entailment
|
protected function parseText(Token\Text $token, Element\Group $group)
{
$text = new Element\Text($token->getText());
$text->setParent($group);
$group->appendChild($text);
return;
}
|
Parses a text token
@param Jstewmc\Rtf\Token\Text $token a text token
@param Jstewmc\Rtf\Element\Group $group the current group
@return void
@since 0.1.0
|
entailment
|
public function appendChild(Element $element)
{
$this->beforeInsert($element);
array_push($this->children, $element);
$this->afterInsert();
return $this;
}
|
Appends a child element to this group
@param Jstewmc\Rtf\Element $element the element to append
@return self
@since 0.1.0
|
entailment
|
public function getChild($index)
{
if (is_numeric($index) && is_int(+$index)) {
if (array_key_exists($index, $this->children)) {
return $this->children[$index];
} else {
throw new \OutOfBoundsException(
__METHOD__."() expects parameter one, index, to be a valid key"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, index, to be an integer"
);
}
return null;
}
|
Returns the child element with $index or null if child does not exist
@param int $index the index of the desired child element (0-based)
@return Jstewmc\Rtf\Element|null
@throws InvalidArgumentException if $index is not an integer
@throws OutOfBoundsException if $index is not an existing key
@since 0.1.0
|
entailment
|
public function getControlWords($word, $parameter = null)
{
$words = [];
// if $word is a string
if (is_string($word)) {
// if $parameter is null, false, or an integer
$isNull = $parameter === null;
$isFalse = $parameter === false;
$isInt = is_numeric($parameter) && is_int(+$parameter);
if ($isNull || $isFalse || $isInt) {
// loop through the group's children
foreach ($this->children as $child) {
// if the child is a group, call the method recursively
// otherwise, if the child is a word, check its word and parameter
//
if ($child instanceof Group) {
$words = array_merge($words, $child->getControlWords($word, $parameter));
} elseif ($child instanceof Control\Word\Word) {
// if the words match
if ($child->getWord() == $word) {
// if the parameter is ignored, correctly undefined or equal, append the child
$isIgnored = $parameter === null;
$isUndefined = $parameter === false && $child->getParameter() === null;
$isEqual = $child->getParameter() == $parameter;
if ($isIgnored || $isUndefind || $isEqual) {
$words[] = $child;
}
}
}
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter two, parameter, to be false, null, or integer"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, word, to be a string"
);
}
return $words;
}
|
Returns an array of control words with $word and, optionally, $parameter
@param string $word the control word's word
@param int|null|false $parameter the control word's integer parameter,
null for any parameter, or false for no parameter (optional; if omitted,
defaults to null)
@return Jstewmc\Rtf\Element\Control\Word\Word[]
@throws InvalidArgumentException if $word is not a string
@throws InvalidArgumentException if $parameter is not a null, false, or number
@since 0.1.0
|
entailment
|
public function getControlSymbols($symbol, $parameter = null)
{
$symbols = [];
// if $symbol is a string
if (is_string($symbol)) {
// if $parameter is null, false, or a string
if ($parameter === null || $parameter === false || is_string($parameter)) {
// loop through the group's children
foreach ($this->children as $child) {
// if the child is a group, call the method recursively
// otherwise, if the child is a word, check its word and parameter
//
if ($child instanceof Group) {
$symbols = array_merge($symbols, $child->getControlSymbols($symbol, $parameter));
} elseif ($child instanceof Control\Symbol\Symbol) {
// if the words match
if ($child->getSymbol() == $symbol) {
// if the parameter is ignored, correctly undefined or equal, append the child
$isIgnored = $parameter === null;
$isUndefined = $parameter === false && $child->getParameter() === null;
$isEqual = $child->getParameter() == $parameter;
if ($isIgnored || $isUndefind || $isEqual) {
$symbols[] = $child;
}
}
}
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter two, parameter, to be false, null, or string"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, symbol, to be a string"
);
}
return $symbols;
}
|
Returns an array of control symbol elements with $symbol and, optionally,
$parameter
@param string $symbol the symbol's symbol
@param string|null|false $parameter the symbol's string parameter; null,
any parameter; or, false, no parameter (optional; if omitted, defaults to
null)
@return Jstewc\Element\Control\Symbol\Symbol[]
@throws InvalidArgumentException if $word is not a string
@throws InvalidArgumentException if $parameter is not a string or null
@since 0.1.0
|
entailment
|
public function getChildIndex(Element $element)
{
foreach ($this->children as $k => $child) {
if ($child === $element) {
return $k;
}
}
return false;
}
|
Returns the child's index in this group's children (if it exists)
Warning! This method may return a boolean false, but it may also return an
integer value that evaluates to false. Use the strict comparison operator,
"===" when testing the return value of this method.
@param Jstewm\Rtf\Element\Element $element the element to find
@return int|false
|
entailment
|
public function hasChild($one, $two = null)
{
$hasChild = false;
// if the first argument is an Element or an index
$isOneElement = $one instanceof Element;
$isOneIndex = is_numeric($one) && is_int(+$one);
if ($isOneElement || $isOneIndex) {
// if the second argument is null, an Element, or an Index
$isTwoNull = $two === null;
$isTwoElement = $two instanceof Element;
$isTwoIndex = is_numeric($two) && is_int(+$two);
if ($isTwoNull || $isTwoElement || $isTwoIndex) {
// decide what to do
if ($isOneElement && $isTwoNull) {
// return true if *the* element exists at *any* index
$hasChild = $this->getChildIndex($one) !== false;
} elseif ($isOneElement && $isTwoIndex) {
// return true if *the* element exists at *the* index
$hasChild = $this->getChildIndex($one) === $two;
} elseif ($isOneIndex && $isTwoNull) {
// return true if *any* element exists at *the* index
$hasChild = array_key_exists($one, $this->children)
&& ! empty($this->children[$one]);
} elseif ($isOneIndex && $isTwoElement) {
// return true if *the* element exists at *the* index
$hasChild = $this->getChildIndex($two) === $one;
} else {
throw new \BadMethodCallException(
__METHOD__."() expects one or two parameters: an element, an index, or both "
. "(in any order)"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter two to be null, Element, or integer"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one to be an Element or integer"
);
}
return $hasChild;
}
|
Returns true if the group has the child
I'll accept one or two arguments: if both an element and an index are given
(in any order), I'll return true if *the* element exists at the index; if
only an element is given, I'll return true if the element exists at *any*
index; and, finally, if only an index is given, I'll return true if *any*
element exists at the index.
@param Jstewmc\Rtf\Element|integer $one the element or index to test
@param Jstewmc\Rtf\Element|integer|null $two the element or index to test
(optional; if omitted, defaults to null)
@return bool
@throws InvalidArgumentException if $one is not an element or integer
@throws InvalidArgumentException if $two is not null, an element, or an
integer
@throws BadMethodCallException if an element, and element or both are not
given
@since 0.1.0
|
entailment
|
public function insertChild(Element $element, $index)
{
// if $index is an integer
if (is_numeric($index) && is_int(+$index)) {
// if index is a valid key
if (array_key_exists($index, $this->children)) {
$this->beforeInsert($element);
array_splice($this->children, $index, 0, [$element]);
$this->afterInsert();
} elseif ($index == count($this->children)) {
$this->appendChild($element);
} elseif ($index == 0) {
$this->prependChild($element);
} else {
throw new \OutOfBoundsException(
__METHOD__."() expects parameter two, index, to be a valid key; one higher"
. "than the highest key; or, zero"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter two, index, to be an integer"
);
}
return $this;
}
|
Inserts a child element at $index
I'll accept a valid key, and insert the element there; a value one higher than
the highest key, and I'll append the element to the end of the array; or, zero,
and I'll prepend the element to the beginning of the array.
@param Jstewmc\Rtf\Element\Element $element the child element to insert
@param int $index the child's index
@return self
@throws InvalidArgumentException if $index is not a numeric index
@throws OutOfBoundsException if $index is not a valid key; one higher than
the highest key; or, zero
@since 0.1.0
|
entailment
|
public function render()
{
// set the group's render flag to false
$this->isRendered = false;
// loop through the group's children
foreach ($this->children as $k => $child) {
// get the child's (starting) style...
//
// if this child is the first-child, it inherits the group's style; otherwise,
// it inherits the previous child's (ending) style
//
if ($k == 0) {
$style = $this->style;
} else {
$previous = $this->children[$k - 1];
$style = $previous->getStyle();
}
// set the child's style...
//
// be sure to clone the style to create a distinct copy of the child's state;
// otherwise, changes to the child's state will affect the group's state,
// and the group's (ending) state will be the last child's (ending) state
//
$child->setStyle(clone $style);
// if the child is a group, render it
// otherwise, if the child is a control word or symbol, run it
//
if ($child instanceof Group) {
$child->render();
} elseif ($child instanceof Control\Control) {
$child->run();
}
// finally, merge the (ending) state of the current child with the (ending)
// state of the previous sibling (to save memory)
//
$child->getStyle()->merge($style);
}
// set the group's flag to true
$this->isRendered = true;
return;
}
|
Renders the group
@return void
|
entailment
|
public function prependChild(Element $element)
{
$this->beforeInsert($element);
array_unshift($this->children, $element);
$this->afterInsert();
return $this;
}
|
Prepends a child element to the group
@param Jstewmc\Rtf\Element $element the child element to prepend
@return self
@since 0.1.0
|
entailment
|
public function removeChild($element)
{
$removed = null;
// if $element is an integer or element
$isInteger = is_numeric($element) && is_int(+$element);
$isElement = $element instanceof Element;
if ($isInteger || $isElement) {
// get the element's index
if ($isElement) {
$index = $this->getChildIndex($element);
} else {
$index = $element;
}
// if the index exists
if ($index !== false && array_key_exists($index, $this->children)) {
$this->beforeDelete();
$removed = reset(array_splice($this->children, $index, 1));
$this->afterDelete($removed);
} else {
throw new \OutOfBoundsException(
__METHOD__."() expects parameter one, element, to be a valid child element or key"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, index, to be an integer or element instance"
);
}
return $removed;
}
|
Removes a child from the parent (and returns it)
@param Jstewmc\Rtf\Element|int $element the child element or integer index
to remove
@return Jstewmc\Rtf\Element|null the removed element
@throws InvalidArgumentException if $index is not an intger
@throws OutOfBoundsException if $index is not an existing key
@since 0.1.0
|
entailment
|
public function replaceChild($old, Element $new)
{
$replaced = null;
// if $old is an integer or element
$isInteger = is_numeric($old) && is_int(+$old);
$isElement = $old instanceof Element;
if ($isInteger || $isElement) {
// get the element's index
if ($isElement) {
$index = $this->getChildIndex($old);
} else {
$index = $old;
}
// if the index exists
if ($index !== false && array_key_exists($index, $this->children)) {
$this->beforeInsert($new);
$replaced = reset(array_splice($this->children, $index, 1, [$new]));
$this->afterDelete($replaced);
} else {
throw new \OutOfBoundsException(
__METHOD__."() expects parameter two, index, to be a valid key or child element"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter two, index, to be an integer or element"
);
}
return $replaced;
}
|
Replaces the the $old with $new (and returns replaced element)
@param Jstewmc\Rtf\Element|int $old the element to be replaced or an integer
index
@param Jstewmc\Rtf\Element $new the replacement element
@return self
@throws InvalidArgumentException if $index is not an integer or element
@throws OutOfBoundsException if $index is not an existing key or child
element
@since 0.1.0
|
entailment
|
public function toHtml()
{
$html = '';
// if this group isn't a destination
if ( ! $this->isDestination()) {
// set the first element's "old" style to the group's style
$oldStyle = $this->style;
// define a flag indicating whether or not this group is the root group
//
// setting this flag here feel a little hackish!
// however, the first element in the first group is different than the first
// element in any other group
//
$isFirstGroup = empty($this->parent);
// a flag indicating whether or not the element is the first "textual" element
// in the group (i.e., control word with a special symbol, an actual text
// element, etc)
//
$isFirstTextualElement = true;
// loop through the group's children
foreach ($this->children as $child) {
// if the child is a textual element
$string = $child->format('html');
if ( ! empty($string)) {
// get the child's style
$newStyle = $child->getStyle();
// if the child is the first textual element in the first (aka, "root") group
if ($isFirstGroup && $isFirstTextualElement) {
// open the document's first section, paragraph, and character tags
$html .= '<section style="'.$newStyle->getSection()->format('css').'">'
. '<p style="'.$newStyle->getParagraph()->format('css').'">'
. '<span style="'.$newStyle->getCharacter()->format('css').'">';
// set the flag to false
$isFirstTextualElement = false;
} else {
// otherwise, the child is not the first textual element in the root group
// and we only close and open the section, paragraph, and character tags
// if the style has changed between elements
//
// keep in mind, a section takes precedence over a paragraph and a character;
// a paragraph takes precedence over a character; so on and so forth
//
if ($oldStyle->getSection() != $newStyle->getSection()) {
$html .= '</span></p></section>'
. '<section style="'.$newStyle->getSection()->format('css').'">'
. '<p style="'.$newStyle->getParagraph()->format('css').'">'
. '<span style="'.$newStyle->getCharacter()->format('css').'">';
} elseif ($oldStyle->getParagraph() != $newStyle->getParagraph()) {
$html .= '</span></p>'
. '<p style="'.$newStyle->getParagraph()->format('css').'">'
. '<span style="'.$newStyle->getCharacter()->format('css').'">';
} elseif ($oldStyle->getCharacter() != $newStyle->getCharacter()) {
$html .= '</span>'
. '<span style="'.$newStyle->getCharacter()->format('css').'">';
}
}
// append the html string
$html .= $string;
// set the "old" style to the current element's style for the next iteration
$oldStyle = $newStyle;
}
}
}
return $html;
}
|
Returns the group as an html5 string
@return string
@since 0.1.0
|
entailment
|
public function toRtf()
{
$rtf = '{';
foreach ($this->children as $child) {
$rtf .= $child->format('rtf');
}
$rtf .= '}';
return $rtf;
}
|
Returns the group as an rtf string
@return string
@since 0.1.0
|
entailment
|
public function toText()
{
$text = '';
// if this group is not a destination
if ( ! $this->isDestination()) {
foreach ($this->children as $child) {
$text .= $child->format('text');
}
}
return $text;
}
|
Returns the group as plain text
@return string
@since 0.1.0
|
entailment
|
public function run()
{
$this->style->getCharacter()->setIsBold(
$this->parameter === null || (bool) $this->parameter
);
return;
}
|
Runs the command
@return void
|
entailment
|
public function render(Element\Group $root)
{
// create a new, blank style
$style = new Style();
// render the root and its branches, recursively
$root->setStyle($style);
$root->render();
return $root;
}
|
Renders the parse tree into a document
@param Jstewmc\Rtf\Element\Group $root the parse tree's root group
@return Jstewmc\Rtf\Element\Group the render tree's root group
@since 0.1.0
|
entailment
|
public function load($source)
{
// if $source is not a string, short-circuit
if ( ! is_string($source)) {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, source, to be a string file name"
);
}
// otherwise, create a new file chunker
$chunker = new \Jstewmc\Chunker\File($source);
return $this->create($chunker);
}
|
Creates a document from a file
@param string $source the source's file name
@return bool true on success or false on failure
@throws InvalidArgumentException if $source is not a string
@throws InvalidArgumentException if $source does not exist or is not readable
@since 0.1.0
|
entailment
|
public function read($string)
{
// if $string is not a string, short-circuit
if ( ! is_string($string)) {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, string, to, er, be a string"
);
}
// otherwise, create a new text chunker
$chunker = new \Jstewmc\Chunker\Text($string);
return $this->create($chunker);
}
|
Creates a document from a string
@param string $string the source string
@return bool true if great success!
@throws InvalidArgumentException if $string is not a string
@since 0.1.0
|
entailment
|
public function save($destination, $format = null)
{
$isSuccess = false;
// if $destination is a string
if (is_string($destination)) {
// if $format is null or a string
if ($format === null || is_string($format)) {
// if format is null
if ($format === null) {
// get the format from the destination's file name
$period = strrpos($destination, '.');
$extension = substr($destination, $period + 1);
switch (strtolower($extension)) {
case 'htm':
case 'html':
$format = 'html';
break;
case 'rtf':
$format = 'rtf';
break;
case 'txt':
$format = 'text';
break;
default:
throw new \BadMethodCallException(
__METHOD__."() expects parameter one, destination, to end in '.htm', "
. "'.html', '.rtf', or '.txt' if parameter two, format, is null"
);
}
}
// put the document's contents
$isSuccess = (bool) file_put_contents($destination, $this->write($format));
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter two, format, to be 'html', 'rtf', 'text', or null"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, destination, to be a string file name"
);
}
return $isSuccess;
}
|
Saves the document to $destination
@param string $destination the destination's file name
@param string|null $format the file's format (possible string values
are 'html', 'rtf', and 'text') (optional; if omitted, defaults to null
and the file's format is assumed from the file name)
@return bool
@throws InvalidArgumentException if $destination is not a string
@throws InvalidArgumentException if $format is not a string or null
@throws BadMethodCallException if $format is null and $destination does
not end in '.htm', '.html', '.rtf', or '.txt'
@since 0.1.0
|
entailment
|
public function write($format = 'rtf')
{
$string = '';
// if $format is a string
if (is_string($format)) {
$writer = new Writer();
$string = $writer->write($this->root, $format);
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, format, to be a string"
);
}
return $string;
}
|
Returns the document as a string
@param string $format the desired format (optional; if omitted, defaults
to 'rtf')
@return string
@throws InvalidArgumentException if $format is not a string
@since 0.1.0
|
entailment
|
protected function create(\Jstewmc\Chunker\Chunker $chunker)
{
// create the document's stream
$stream = new \Jstewmc\Stream\Stream($chunker);
// lex the string into tokens
$lexer = new Lexer();
$tokens = $lexer->lex($stream);
// if tokens exist
if ( ! empty($tokens)) {
// parse the tokens into the parse tree's root group
$parser = new Parser();
$group = $parser->parse($tokens);
// if a root exists
if ($group !== null) {
// render the parse tree's root into the document root
$renderer = new Renderer();
$this->root = $renderer->render($group);
} else {
$this->root = null;
}
} else {
$this->root = null;
}
return (bool) $this->root;
}
|
Creates the document
If the stream has no tokens, I'll clear the document's root.
@param Jstewmc\Chunker\Chunker $chunker the document's file or text chunker
@return bool
|
entailment
|
public function run()
{
// if the control word has a previous text element
if (null !== ($text = $this->getPreviousText())) {
// if the last character in the text is the space character
if (substr($text->getText(), -1, 1) == ' ') {
// remove it
$text->setText(substr($text->getText(), 0, -1));
}
}
// if the control word has a next text element
if (null !== ($text = $this->getNextText())) {
// if the first character in the text is the space character
if (substr($text->getText(), 0, 1) == ' ') {
// remove it
$text->setText(substr($text->getText(), 1));
}
}
return;
}
|
Runs the command
@return void
|
entailment
|
public function run()
{
return $this->style->getCharacter()->setIsStrikethrough(
$this->parameter === null || (bool) $this->parameter
);
}
|
Runs the command
@return void
|
entailment
|
public function run()
{
$this->style->getCharacter()->setIsUnderline(
$this->parameter === null || (bool) $this->parameter
);
return;
}
|
Runs the command
@return void
|
entailment
|
public static function createFromStream(\Jstewmc\Stream\Stream $stream)
{
$token = false;
// loop through the characters until a group-open, group-close, control word,
// or control symbol occurs and append the plain-text
//
$text = '';
while (false !== ($character = $stream->current())) {
// if the current characer isn't ignored
if ( ! in_array($character, ["\n", "\r", "\f", "\0"])) {
// if the current character is a backslash
if ($character == '\\') {
// if the next character exists
if (false !== ($next = $stream->next())) {
// if the next character is a control character
if (in_array($next, ['\\', '{', '}'])) {
// it's a literal control character
// ignore the backslash and append the character
//
$text .= $next;
} else {
// otherwise, the backslash is the start of a control word
// rollback two characters (i.e., put the pointer on the character before
// the control word's backslash)
//
$stream->previous();
$stream->previous();
break;
}
} else {
// hmmm, do nothing?
}
} elseif ($character == '{' || $character == '}') {
// otherwise, the current group is closing or a sub-group is opening
// rollback to the previous character (so it isn't consumed)
//
$stream->previous();
break;
} else {
// otherwise, it's text!
$text .= $character;
}
}
// advance to the next character
$stream->next();
}
// if $text is not empty, create a new token
// keep in mind, empty() will consider '0'to be empty, and it's a valid value
//
if ( ! empty($text) || $text === '0') {
$token = new Text($text);
}
return $token;
}
|
Creates a new text token from a stream
@param Jstewmc\Stream\Stream $stream a stream of characters
@return Jstewmc\Rtf\Token\Text|false
@since 0.1.0
@since 0.2.0 renamed from createFromSource() to createFromStream();
replaced argument $characters, an array of characters, with $stream, an
instance of Jstewmc\Stream
|
entailment
|
public function lexAll(\Jstewmc\Stream\Stream $stream)
{
$tokens = [];
// while tokens exist
while (false !== ($token = $this->lexOne($stream))) {
// append le token
$tokens[] = $token;
}
return $tokens;
}
|
Lexes all tokens from the current stream
Keep in mind, for very large documents, this may cause a memory overflow.
@param Jstewmc\Stream\Stream $stream the character stream
@return Jstewmc\Rtf\Token\Token[]
@since 0.2.0
|
entailment
|
public function lexOne(\Jstewmc\Stream\Stream $stream)
{
$token = false;
// if the stream has characters
if ($stream->hasCharacters()) {
// switch on the current character
switch ($stream->current()) {
case '{':
$token = $this->lexOpenBracket($stream);
break;
case '}':
$token = $this->lexCloseBracket($stream);
break;
case '\\':
$token = $this->lexBackslash($stream);
break;
case "\t":
$token = $this->lexTab($stream);
break;
case "\n":
case "\r":
case "\f":
case "\0":
$token = $this->lexOther($stream);
break;
default:
$token = $this->lexText($stream);
}
// advance the stream to the next character
$stream->next();
}
return $token;
}
|
Lexes one token from the current stream
I'll leave the stream's pointer on the first character after the token's last
character. For example, if the stream is "\foo bar", I'll leave the stream on
"b" (because the space is part of the control word).
@param Jstewmc\Stream\Stream $stream the character stream
@return Jstewmc\Rtf\Token\Token|false
@since 0.2.0
|
entailment
|
protected function lexBackslash(\Jstewmc\Stream\Stream $stream)
{
if ($stream->current() !== '\\') {
throw new \InvalidArgumentExeption(
__METHOD__."() expects the current character in the stream to be a '\\'"
);
}
// look ahead to the next character, it'll determine what we do; just be sure
// you rollback to the current character
//
$next = $stream->next();
$stream->previous();
// if a next character exists
if ($next !== false) {
// the next character may be a literal character, an escaped new-line or
// carriage-return (i.e., an implicit "\par" control word), a control
// word, or a control symbol
//
if (in_array($next, ['\\', '{', '}'])) {
$token = Token\Text::createFromStream($stream);
} elseif ($next == "\n" || $next == "\r") {
$token = new Token\Control\Word('par');
$stream->next(); // consume the current "\" character
} elseif (ctype_alpha($next)) {
$token = Token\Control\Word::createFromStream($stream);
} else {
$token = Token\Control\Symbol::createFromStream($stream);
}
}
return $token;
}
|
Lexes the backslash character ("\")
The backslash character ("\") is arguably the most important character in the
RTF specification. A backslash character can indicate the following:
1. a control word (e.g., "\foo")
2. a control symbol (e.g., "\-")
3. an escaped special character (e.g., "\\")
4. an escaped new-line or carriage return (e.g., "\\n")
@param Jstewmc\Stream\Stream $stream the character stream
@return Jstewmc\Rtf\Token\Token|false
@throws InvalidArgumentException if the current character in $stream is not
the backslash character ("\")
@since 0.2.0
|
entailment
|
protected function lexCloseBracket(\Jstewmc\Stream\Stream $stream)
{
if ($stream->current() !== '}') {
throw new \InvalidArgumentException(
__METHOD__."() expects the current character in the stream to be a '}'"
);
}
return new Token\Group\Close();
}
|
Lexes a close-bracket character ("}")
The close-bracket character indicates the end of a group.
@param Jstewmc\Stream\Stream $stream the character stream
@return Jstewmc\Token\Group\Close
@throws InvalidArgumentException if the current character in $stream is not a
an close-bracket character ("}")
@since 0.2.0
|
entailment
|
protected function lexOpenBracket(\Jstewmc\Stream\Stream $stream)
{
if ($stream->current() !== '{') {
throw new \InvalidArgumentException(
__METHOD__."() expects the current character in the stream to be a '{'"
);
}
return new Token\Group\Open();
}
|
Lexes an open-bracket character ("{")
The open-bracket character indicates the start of a new group.
@param Jstewmc\Stream\Stream $stream the character stream
@return Jstewmc\Token\Group\Open
@throws InvalidArgumentException if the current character in $stream is not
an open-bracket character
@since 0.2.0
|
entailment
|
protected function lexTab(\Jstewmc\Stream\Stream $stream)
{
if ($stream->current() !== "\t") {
throw new \InvalidArgumentException(
__METHOD__."() expects the current character in the stream to be a tab character"
);
}
return new Token\Control\Word('tab');
}
|
Lexes the tab character ("\t")
Tab characters should be converted to "\tab" control words.
@param Jstewmc\Stream\Stream $stream the character stream
@return Jstewmc\Rtf\Token\Control\Word
@throws InvalidArgumentException if the current character in $stream is not
the tab character
@since 0.2.0
|
entailment
|
public function run()
{
// if the control word has a next text element
if (null !== ($text = $this->getNextText())) {
// upper-case the first letter in the text element
$text->setText(ucfirst($text->getText()));
}
return;
}
|
Runs the command
@return void
|
entailment
|
public function run()
{
$this->style->getCharacter()->setIsItalic(
$this->parameter === null || (bool) $this->parameter
);
return;
}
|
Runs the command
@return void
|
entailment
|
public function write(Element\Group $root, $format = 'rtf')
{
$string = '';
// if $format is a string
if (is_string($format)) {
// switch on the format
switch (strtolower($format)) {
case 'html':
$string = $root->format('html');
$string .= '</span></p></section>';
break;
case 'rtf':
$string = $root->format('rtf');
break;
case 'text':
$string = $root->format('text');
break;
default:
throw new \InvalidArgumentException(
__METHOD__."() expects parameter two, format, to be 'html', 'rtf', or 'text'"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter two, format, to be a string"
);
}
return $string;
}
|
Returns the document as a string
@param Jstewmc\Rtf\Element\Group $root the document's root group
@param string $format the desired format (possible values are 'rtf',
'html', and 'text') (optional; if omitted, defaults to 'rtf')
@return string
@throws InvalidArgumentException if $format is not a string
@throws InvalidArgumentException if $format is not 'html', 'rtf', 'text'
@since 0.1.0
|
entailment
|
public static function createFromStream(\Jstewmc\Stream\Stream $stream)
{
$symbol = false;
// if a current character exists
if ($stream->current()) {
// if the current character is a backslash
if ($stream->current() === '\\') {
// if the next character exists
if ($stream->next() !== false) {
// if the now current character is not alphanumeric
if ( ! ctype_alnum($stream->current())) {
// create a new control symbol
$symbol = new Symbol($stream->current());
// if the current character is an apostrophe, get the symbol's parameter
if ($stream->current() === '\'') {
$parameter = $stream->next() . $stream->next();
$symbol->setParameter($parameter);
}
// if the next character is a space, the control symbol is space-delimited,
// and we should set the flag; otherwise, it's not, and we should rollback
// to leave the pointer on the last character in the token (i.e., the
// symbol)
//
if ($stream->next() === ' ') {
$symbol->setIsSpaceDelimited(true);
} else {
$symbol->setIsSpaceDelimited(false);
$stream->previous();
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects the next element in parameter one, characters, to "
. "be a non-alphanumeric character"
);
}
} else {
// hmm, do nothing?
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects the current element in parameter one, characters, to "
. "be the backslash character"
);
}
}
return $symbol;
}
|
Creates a control symbol token from stream
@param Jstewmc\Stream $stream a stream of characters (the current character
must be the backslash character, and the next character should be non-
alphanumeric)
@return Jstewmc\Rtf\Token\Control\Symbol|false
@throws InvalidArgumentException if the current character in $stream is
not a backslash
@throws InvalidArgumentException if the next character in $stream is not
a non-alphanumeric character
@since 0.1.0
@since 0.2.0 renamed from createFromSource() to createFromStream; replaced
argument $characters, an array of characters, with $stream, an instance
of Jstewmc\STream
|
entailment
|
public static function createFromStream(\Jstewmc\Stream\Stream $stream)
{
$token = false;
// if a current character exists
if ($stream->current()) {
// if the current character is the backslash character
if ($stream->current() === '\\') {
// if the next character exists
if ($stream->next() !== false) {
// if the now current character is an alphabetic character
if (ctype_alpha($stream->current())) {
// get the control word's word
$word = self::readWord($stream);
// if the current character is a digit or hyphen, get the word's parameter
if (ctype_digit($stream->current()) || $stream->current() == '-') {
$parameter = self::readParameter($stream);
} else {
$parameter = null;
}
// create the control word token
$token = new Word($word, $parameter);
// if the current character is a space delimiter, set the flag; otherwise,
// it is not a space character, and it should not be consumed; it's the
// start of another token; rollback to the previous character to leave
// the pointer on the last character of this token
//
if ($stream->current() === ' ') {
$token->setIsSpaceDelimited(true);
} else {
$token->setIsSpaceDelimited(false);
$stream->previous();
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects the next element in parameter one, characters, to "
. "be an alphabetic character"
);
}
} else {
// hmmm, do nothing?
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects the current element in parameter one, characters, to "
. "be the backslash character"
);
}
}
return $token;
}
|
Creates a control word token from a stream of characters
@param Jstewmc\Stream $stream a stream of characters (the current character
in $characters must be the backslash character ("\"))
@return Jstewmc\Rtf\Token\Control\Word|false
@throws InvalidArgumentException if the current character in $stream is
not the backslash character ("\")
@throws InvalidArgumentException if the next character in $stream is not
an alphabetic character
@since 0.1.0
@since 0.2.0 renamed from createFromSource() to createFromStream(); replaced
argument $characters, an array of characters, to $stream, an instance of
Jstewmc\Stream
|
entailment
|
protected static function readWord(\Jstewmc\Stream\Stream $stream)
{
$word = '';
// if the current character is an alphabetic character
if (ctype_alpha($stream->current())) {
// loop through the alphabetic characters and build the word
while (ctype_alpha($stream->current())) {
$word .= $stream->current();
$stream->next();
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects the current element in parameter one, characters, "
. "to be an alphabetic character"
);
}
return $word;
}
|
Reads a control word's word from the character stream
@param Jstewmc\Stream $stream a stream of characters (the current character
must be a alphabetic character)
@return string
@throws InvalidArgumentException if the current element in $stream is not
an alphabetic character
@since 0.1.0
@since 0.2.0 replace argument $characters, an array of characters, with $stream
an instance of Jstewmc\Stream
|
entailment
|
protected static function readParameter(\Jstewmc\Stream\Stream $stream)
{
$parameter = '';
// if the current character is a digit or hyphen ("-")
if (ctype_digit($stream->current()) || $stream->current() == '-') {
// determine if the parameter is negative
$isNegative = ($stream->current() == '-');
// if the number is negative, consume the hyphen
if ($isNegative) {
$stream->next();
}
// loop through the digits and append them to the parameter
while (ctype_digit($stream->current())) {
$parameter .= $stream->current();
$stream->next();
}
// evaluate the parameter's numeric value
$parameter = +$parameter;
// if the parameter is negative, negate it
if ($isNegative) {
$parameter = -$parameter;
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects the current element in parameter one, characters, "
. "to be a digit or hyphen"
);
}
return $parameter;
}
|
Reads a control word's parameter from the characters stream
@param Jstewmc\Stream $stream a stream of characters (the current character
must be a digit or hyphen)
@return int
@throws InvalidArgumentException if the current character in $stream is
not a digit or hyphen
@since 0.1.0
@since 0.2.0 replace argument $characters, an array of characters, with $stream
an instance of Jstewmc\Stream
|
entailment
|
public function setCharacter($character)
{
if ( ! is_string($character)) {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, character, to be a string"
);
}
$this->character = $character;
return $this;
}
|
Sets the token's character
@param string $character the "other" character
@return self
@throws InvalidArgumentException if $character is not a string
@since 0.3.0
|
entailment
|
public function setStyle(\Jstewmc\Rtf\Style $style = null)
{
$this->style = $style;
return $this;
}
|
Sets the element's style
@param Jstewmc\Rtf\Style|null $style the element's style
@return self
@since 0.1.0
|
entailment
|
public function getIndex()
{
$index = false;
// if this element has a parent
if ( ! empty($this->parent)) {
$index = $this->parent->getChildIndex($this);
// if we didn't find the child, something is wrong
if ($index === false) {
throw new \BadMethodCallException(
__METHOD__."() expects this element to be a child of its parent"
);
}
} else {
throw new \BadMethodCallException(
__METHOD__."() expects this element to have a parent element"
);
}
return $index;
}
|
Returns this element's index in its parent children
Warning! This method may return a boolean false, but it may also return an
integer value that evaluates to false. Use the strict comparison operator,
"===" when testing the return value of this method.
@return int|false
@throws BadMethodCallException if the element doesn't have a parent
@throws BadMethodCallException if the element's parent doesn't have children
@throws BadMethodCallException if the element is not a child of its parent
@since 0.1.0
|
entailment
|
public function getNextSibling()
{
$next = null;
// if this element has an index
if (false !== ($index = $this->getIndex())) {
// if this element has a next sibling
if ($this->parent->hasChild($index + 1)) {
$next = $this->parent->getChild($index + 1);
}
}
return $next;
}
|
Returns this element's next sibling or null if no sibling exists
@return Jstewmc\Rtf\Element\Element|null
@throws BadMethodCallException if the element doesn't have a parent
@throws BadMethodCallException if the element's parent doesn't have children
@throws BadMethodCallException if the element is not a child of its parent
@since 0.1.0
|
entailment
|
public function getNextText()
{
$text = null;
// get the element's next sibling element
$next = $this->getNextSibling();
// while the next sibling element exists and is not a text element
while ($next !== null && ! $next instanceof \Jstewmc\Rtf\Element\Text) {
$next = $next->getNextSibling();
}
// if a next text element exists
if ($next !== null && $next instanceof \Jstewmc\Rtf\Element\Text) {
$text = $next;
}
return $text;
}
|
Returns this element's next text element or null if no next text element
exists
@return Jstewmc\Rtf\Element\Text|null
@throws BadMethodCallException if the element doesn't have a parent
@throws BadMethodCallException if the element's parent doesn't have children
@throws BadMethodCallException if the element is not a child of its parent
|
entailment
|
public function getPreviousSibling()
{
$previous = null;
// if this element has an index
if (false !== ($index = $this->getIndex())) {
// if this element has a previous sibling
if ($this->parent->hasChild($index - 1)) {
$previous = $this->parent->getChild($index - 1);
}
}
return $previous;
}
|
Returns this element's previous sibling or null if no sibling exists
@return Jstewmc\Rtf\Element\Element|null
@throws BadMethodCallException if the element doesn't have a parent
@throws BadMethodCallException if the element's parent doesn't have children
@throws BadMethodCallException if the element is not a child of its parent
@since 0.1.0
|
entailment
|
public function getPreviousText()
{
$text = null;
// get the element's preivous sibling element
$previous = $this->getPreviousSibling();
// while the previous sibling element exists and is not a text element
while ($previous !== null && ! $previous instanceof \Jstewmc\Rtf\Element\Text) {
$previous = $previous->getPreviousSibling();
}
// if a previous text element exists
if ($previous !== null && $previous instanceof \Jstewmc\Rtf\Element\Text) {
$text = $previous;
}
return $text;
}
|
Returns this element's previous text element or null if not previous text
element exists
@return Jstewmc\Rtf\Element\Text|null
@throws BadMethodCallException if the element doesn't have a parent
@throws BadMethodCallException if the element's parent doesn't have children
@throws BadMethodCallException if the element is not a child of its parent
|
entailment
|
public function format($format = 'rtf')
{
$string = '';
// if $format is a string
if (is_string($format)) {
// switch on the lower-cased format
switch (strtolower($format)) {
case 'html':
$string = $this->toHtml();
break;
case 'rtf':
$string = $this->toRtf();
break;
case 'text':
$string = $this->toText();
break;
default:
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, format, to be 'rtf', 'html', or 'text'"
);
}
} else {
throw new \InvalidArgumentException(
__METHOD__."() expects parameter one, format, to be a string"
);
}
return $string;
}
|
Returns the element as a string in $format
@param string $format the desired format (possible values are 'rtf',
'html', and 'text') (optional; if omitted, defaults to 'rtf')
@return string
@throws InvalidArgumentException if $format is not a string
@throws InvalidArgumentException if $format is not 'rtf', 'html', or 'text'
@since 0.1.0
|
entailment
|
public function insertAfter(Element $element)
{
// if $element has an index
if (false !== ($index = $element->getIndex())) {
$element->getParent()->insertChild($this, $index + 1);
}
return $this;
}
|
Inserts this element after $element
@param Jstewmc\Rtf\Element $element the element to insert after
@return self
@throws BadMethodCallException if $element doesn't have a parent
@throws BadMethodCallException if $element's parent doesn't have children
@throws BadMethodCallException if $element is not a child of its parent
@since 0.1.0
|
entailment
|
public function putNextSibling(Element $element)
{
if (false !== ($index = $this->getIndex())) {
$this->parent->insertChild($element, $index + 1);
}
return $this;
}
|
Inserts an element after this element
@param Jstewmc\Rtf\Element\Element $element the element to insert
@return self
@throws BadMethodCallException if the element doesn't have a parent
@throws BadMethodCallException if the element's parent doesn't have children
@throws BadMethodCallException if the element is not a child of its parent
@since 0.1.0
|
entailment
|
public function replaceWith(Element $element)
{
// if the element has a parent
if ( ! empty($this->parent)) {
$this->parent->replaceChild($this, $element);
} else {
throw new \BadMethodCallException(
__METHOD__."() expects this element to have a parent element"
);
}
return $this;
}
|
Replaces this element with $element (and returns this element)
@param Jstewmc\Rtf\Element $element the replacement element
@return Jstewmc\Rtf\Element
@throws BadMethodCallException if this element doesn't have a parent
@since 0.1.0
|
entailment
|
public function run()
{
$this->style->getCharacter()->setIsSuperscript(
$this->parameter === null || (bool) $this->parameter
);
return;
}
|
Runs the command
@return void
|
entailment
|
public function toRtf()
{
// escape special characters
$text = str_replace('\\', '\\\\', $this->text);
$text = str_replace('{', '\{', $text);
$text = str_replace('}', '\}', $text);
return "$text";
}
|
Returns this text as an rtf string
@return string
@since 0.1.0
|
entailment
|
protected function toRtf()
{
$rtf = '';
// if a word exists
if ($this->word) {
// if the word is ignored
if ($this->isIgnored) {
// prepend the ignored control symbol
$rtf = '\\*';
}
// append the word and its parameter
$rtf .= "\\{$this->word}{$this->parameter}";
// if the word is space-delimited, append the space
if ($this->isSpaceDelimited) {
$rtf .= ' ';
}
}
return $rtf;
}
|
Returns this control word as an rtf string
@return string
@since 0.1.0
|
entailment
|
public function autoCompleteAction(Request $request)
{
/** @var Admin $admin */
$admin = $this->pool->getInstance($request->get('code'));
$admin->setRequest($request);
// check user permission
if (false === $admin->isGranted('LIST')) {
throw new AccessDeniedException();
}
// subject will be empty to avoid unnecessary database requests and keep auto-complete function fast
$admin->setSubject($admin->getNewInstance());
$fieldDescription = $this->retrieveFieldDescription($admin, $request->get('field'));
$formAutocomplete = $admin->getForm()->get($fieldDescription->getName());
if ($formAutocomplete->getConfig()->getAttribute('disabled')) {
throw new AccessDeniedException('Autocomplete list can`t be retrieved because the form element is disabled or read_only.');
}
$class = $formAutocomplete->getConfig()->getOption('class');
$property = $formAutocomplete->getConfig()->getAttribute('property');
$minimumInputLength = $formAutocomplete->getConfig()->getAttribute('minimum_input_length');
$itemsPerPage = $formAutocomplete->getConfig()->getAttribute('items_per_page');
$reqParamPageNumber = $formAutocomplete->getConfig()->getAttribute('req_param_name_page_number');
$toStringCallback = $formAutocomplete->getConfig()->getAttribute('to_string_callback');
$searchText = $request->get('q');
if (mb_strlen($searchText, 'UTF-8') < $minimumInputLength) {
return new JsonResponse(['status' => 'KO', 'message' => 'Too short search string.'], 403);
}
$page = $request->get($reqParamPageNumber);
$offset = ($page - 1) * $itemsPerPage;
/** @var ModelManager $modelManager */
$modelManager = $formAutocomplete->getConfig()->getOption('model_manager');
$dm = $modelManager->getDocumentManager();
if ($class) {
/** @var $qb \Doctrine\ODM\PHPCR\Query\Builder\QueryBuilder */
$qb = $dm->getRepository($class)->createQueryBuilder('a');
$qb->where()->fullTextSearch("a.$property", '*'.$searchText.'*');
$qb->setFirstResult($offset);
//fetch one more to determine if there are more pages
$qb->setMaxResults($itemsPerPage + 1);
$query = $qb->getQuery();
$results = $query->execute();
} else {
/** @var $qb \PHPCR\Util\QOM\QueryBuilder */
$qb = $dm->createPhpcrQueryBuilder();
// TODO: node type should probably be configurable
$qb->from($qb->getQOMFactory()->selector('a', 'nt:unstructured'));
$qb->where($qb->getQOMFactory()->fullTextSearch('a', $property, '*'.$searchText.'*'));
// handle attribute translation
$qb->orWhere($qb->getQOMFactory()->fullTextSearch('a', $dm->getTranslationStrategy('attribute')->getTranslatedPropertyName($request->getLocale(), $property), '*'.$searchText.'*'));
$qb->setFirstResult($offset);
//fetch one more to determine if there are more pages
$qb->setMaxResults($itemsPerPage + 1);
$results = $dm->getDocumentsByPhpcrQuery($qb->getQuery());
}
//did we max out x+1
$more = (\count($results) == $itemsPerPage + 1);
$method = $request->get('_method_name');
$items = [];
foreach ($results as $path => $document) {
// handle child translation
if (0 === strpos(PathHelper::getNodeName($path), Translation::LOCALE_NAMESPACE.':')) {
$document = $dm->find(null, PathHelper::getParentPath($path));
}
if (!method_exists($document, $method)) {
continue;
}
$label = $document->{$method}();
if (null !== $toStringCallback) {
if (!\is_callable($toStringCallback)) {
throw new \RuntimeException('Option "to_string_callback" does not contain callable function.');
}
$label = \call_user_func($toStringCallback, $document, $property);
}
$items[] = [
'id' => $admin->id($document),
'label' => $label,
];
}
return new JsonResponse([
'status' => 'OK',
'more' => $more,
'items' => $items,
]);
}
|
@param Request $request
@throws AccessDeniedException
@return Response
|
entailment
|
private function retrieveFieldDescription(AdminInterface $admin, $field)
{
$admin->getFormFieldDescriptions();
$fieldDescription = $admin->getFormFieldDescription($field);
if (!$fieldDescription) {
throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field));
}
if ('sonata_type_model_autocomplete' !== $fieldDescription->getType()) {
throw new \RuntimeException(sprintf('Unsupported form type "%s" for field "%s".', $fieldDescription->getType(), $field));
}
return $fieldDescription;
}
|
Retrieve the field description given by field name.
@param AdminInterface $admin
@param string $field
@throws \RuntimeException
@return \Symfony\Component\Form\FormInterface
|
entailment
|
public function run(CommandInterface $command, $result = null)
{
if(!$result instanceof ResponseInterface) {
throw new \InvalidArgumentException(
'The result needs to be an instance of GuzzleHttp\Message\ResponseInterface');
}
return json_decode($result->getBody()->getContents(), true);
}
|
{@inheritdoc}
@param \Psr\Http\Message\ResponseInterface $result
|
entailment
|
public function build(AdminInterface $admin, RouteCollection $collection)
{
$collection->add('list');
$collection->add('create');
$collection->add('batch', null, [], [], [], '', [], ['POST']);
$collection->add('edit', $admin->getRouterIdParameter().'/edit', [], ['id' => '.+']);
$collection->add('delete', $admin->getRouterIdParameter().'/delete', [], ['id' => '.+']);
$collection->add('export');
$collection->add('show', $admin->getRouterIdParameter().'/show', [], ['id' => '.+'], [], '', [], ['GET']);
if ($admin->isAclEnabled()) {
$collection->add('acl', $admin->getRouterIdParameter().'/acl', [], ['id' => '.+']);
}
// add children urls
foreach ($admin->getChildren() as $children) {
$collection->addCollection($children->getRoutes());
}
}
|
RouteBuilder that allows slashes in the ids.
{@inheritdoc}
|
entailment
|
protected function fixSettings(ContainerBuilder $container)
{
$pool = $container->getDefinition('sonata.admin.manager.doctrine_phpcr');
// @todo not very clean but don't know how to do that for now
$settings = false;
$methods = $pool->getMethodCalls();
foreach ($methods as $pos => $calls) {
if ('__hack_doctrine_phpcr__' == $calls[0]) {
$settings = $calls[1];
break;
}
}
if ($settings) {
unset($methods[$pos]);
}
$pool->setMethodCalls($methods);
return $settings;
}
|
@param ContainerBuilder $container
@return bool
|
entailment
|
public function setGameMode($gameMode)
{
$gameMode = (int) $gameMode;
if($gameMode < 0 || $gameMode > 16) {
throw new \InvalidArgumentException('Invalid game mode. Must be between 0 and 16');
}
$this->gameMode = $gameMode;
return $this;
}
|
@param int $gameMode
@return self
|
entailment
|
public function setSkill($skill)
{
$skill = (int) $skill;
if($skill < 0 || $skill > 3) {
throw new \InvalidArgumentException('Invalid skill. Must be between 0 and 3');
}
$this->skill = $skill;
return $this;
}
|
@param int $skill
@return self
|
entailment
|
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setRequired(['root']);
if (method_exists($resolver, 'setDefined')) {
// The new OptionsResolver API
$resolver->setDefined(['create_in_overlay', 'edit_in_overlay', 'delete_in_overlay']);
} else {
// To keep compatibility with old Symfony <2.6 API
$resolver->setOptional(['create_in_overlay', 'edit_in_overlay', 'delete_in_overlay']);
}
$resolver->setDefaults([
'create_in_overlay' => true,
'edit_in_overlay' => true,
'delete_in_overlay' => true,
]);
}
|
{@inheritdoc}
|
entailment
|
public function enhance(Description $description)
{
$nodePath = $description->getResource()->getPath();
$nodeName = PathHelper::getNodeName($nodePath);
$parentPath = PathHelper::getParentPath($nodePath);
try {
$parentNode = $this->session->getNode($parentPath);
} catch (PathNotFoundException $exception) {
return false;
}
$nodeIterator = $parentNode->getNodes();
$nodeIterator->rewind();
$counter = 0;
while ($nodeIterator->valid()) {
++$counter;
if ($nodeIterator->key() === $nodeName) {
break;
}
$nodeIterator->next();
}
$description->set('position', $counter);
}
|
{@inheritdoc}
|
entailment
|
public function supports(PuliResource $resource)
{
if (!$resource instanceof CmfResource) {
return false;
}
try {
$parentNode = $this->session->getNode(PathHelper::getParentPath($resource->getPath()));
} catch (PathNotFoundException $exception) {
return false;
}
// Todo: check for non orderable type
return true;
}
|
{@inheritdoc}
|
entailment
|
private function loadDocumentTree($config, ContainerBuilder $container)
{
$configuration = [
'routing_defaults' => $config['routing_defaults'],
'repository_name' => $config['repository_name'],
'sortable_by' => $config['sortable_by'],
'move' => true,
'reorder' => true,
];
$container->setParameter('sonata_admin_doctrine_phpcr.tree_block.configuration', $configuration);
foreach ($configuration as $key => $value) {
$container->setParameter('sonata_admin_doctrine_phpcr.tree_block.'.$key, $value);
}
}
|
Set the document tree parameters and configuration.
@param array $config
@param ContainerBuilder $container
|
entailment
|
public function run(CommandInterface $command, $result = null)
{
return parent::run($command, $result)->wait();
}
|
{@inheritdoc}
@return ResponseInterface
|
entailment
|
public function filter(ProxyQueryInterface $proxyQuery, $alias, $field, $data)
{
if (!$data || !\is_array($data) || !isset($data['value'])) {
return;
}
$data['type'] = $data['type'] ?? DateType::TYPE_EQUAL;
$where = $this->getWhere($proxyQuery);
$from = $data['value'];
$to = new \DateTime($from->format('Y-m-d').' +86399 seconds'); // 23 hours 59 minutes 59 seconds
switch ($data['type']) {
case DateType::TYPE_GREATER_EQUAL:
$where->gte()->field('a.'.$field)->literal($from);
break;
case DateType::TYPE_GREATER_THAN:
$where->gt()->field('a.'.$field)->literal($from);
break;
case DateType::TYPE_LESS_EQUAL:
$where->lte()->field('a.'.$field)->literal($from);
break;
case DateType::TYPE_LESS_THAN:
$where->lt()->field('a.'.$field)->literal($from);
break;
case DateType::TYPE_NULL:
$where->eq()->field('a.'.$field)->literal(null);
break;
case DateType::TYPE_NOT_NULL:
$where->neq()->field('a.'.$field)->literal(null);
break;
case DateType::TYPE_EQUAL:
default:
$where->andX()
->gte()->field('a.'.$field)->literal($from)->end()
->lte()->field('a.'.$field)->literal($to)->end();
}
// filter is active as we have now modified the query
$this->active = true;
}
|
{@inheritdoc}
|
entailment
|
public function onSubmit(FormEvent $event)
{
$form = $event->getForm()->getParent();
$data = $form->getData();
if (!\is_object($data)) {
return;
}
$accessor = PropertyAccess::createPropertyAccessor();
$newCollection = $accessor->getValue($data, $this->name);
if (!$newCollection instanceof Collection) {
return;
}
/* @var $newCollection Collection */
$newCollection->clear();
/** @var $item FormBuilder */
foreach ($form->get($this->name) as $key => $item) {
if ($item->get('_delete')->getData()) {
// do not re-add a deleted child
continue;
}
if ($item->getName() && !is_numeric($item->getName())) {
// keep key in collection
$newCollection[$item->getName()] = $item->getData();
} else {
$newCollection[] = $item->getData();
}
}
}
|
Reorder the children of the parent form data at $this->name.
For whatever reason we have to go through the parent object, just
getting the collection from the form event and reordering it does
not update the stored order.
@param FormEvent $event
|
entailment
|
public function filter(ProxyQueryInterface $proxyQuery, $alias, $field, $data)
{
if (!$data || !\is_array($data) || !\array_key_exists('value', $data)) {
return;
}
$data['value'] = trim((string) $data['value']);
$data['type'] = empty($data['type']) ? ChoiceType::TYPE_CONTAINS : $data['type'];
if (0 == \strlen($data['value'])) {
return;
}
$where = $this->getWhere($proxyQuery);
switch ($data['type']) {
case ChoiceType::TYPE_EQUAL:
$where->eq()->localName($alias)->literal($data['value']);
break;
case ChoiceType::TYPE_CONTAINS:
default:
$where->like()->localName($alias)->literal('%'.$data['value'].'%');
}
// filter is active as we have now modified the query
$this->active = true;
}
|
{@inheritdoc}
|
entailment
|
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addViewTransformer(new ModelToIdTransformer($options['model_manager'], $options['class']), true);
$builder->setAttribute('root_node', $options['root_node']);
$builder->setAttribute('select_root_node', $options['select_root_node']);
$builder->setAttribute('repository_name', $options['repository_name']);
}
|
{@inheritdoc}
|
entailment
|
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['root_node'] = $form->getConfig()->getAttribute('root_node');
$view->vars['select_root_node'] = $form->getConfig()->getAttribute('select_root_node');
$view->vars['repository_name'] = $form->getConfig()->getAttribute('repository_name');
$view->vars['routing_defaults'] = $this->defaults;
}
|
{@inheritdoc}
|
entailment
|
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'template' => 'doctrine_phpcr_odm_tree',
'compound' => false,
'model_manager' => null,
'class' => null,
'property' => null,
'query' => null,
'choices' => null,
'root_node' => '/',
'select_root_node' => false,
'parent' => 'choice',
'repository_name' => 'default',
'preferred_choices' => [],
'choice_list' => function (Options $options, $previousValue) {
return new ModelChoiceList(
$options['model_manager'],
$options['class'],
$options['property'],
$options['query'],
$options['choices']
);
},
]);
}
|
{@inheritdoc}
|
entailment
|
public function addRunner(RunnerInterface $runner)
{
$this->runners[] = $runner->setConfig($this->config);
return $this;
}
|
@param RunnerInterface $runner
@return self
|
entailment
|
public function run(CommandInterface $command)
{
$result = null;
/** @var RunnerInterface $runner */
foreach($this->runners as $runner) {
$result = $runner->run($command, $result);
}
return $result;
}
|
@param CommandInterface $command
@return mixed
|
entailment
|
public function run(CommandInterface $command, $result = null)
{
$key = $command->getRequestMethod() === 'GET' ? 'query' : 'body';
$options = [$key => []];
if(!empty($params = $command->getParams())) {
$options[$key] = array_merge($options[$key], $params);
}
if($config = $this->getConfig()) {
if(!empty($config->getSteamKey())) {
$options[$key]['key'] = $config->getSteamKey();
}
$this->urlBuilder->setBaseUrl($config->getBaseSteamApiUrl());
}
$request = new Request(
$command->getRequestMethod(),
$this->urlBuilder->build($command)
);
return $this->client->sendAsync($request, $options);
}
|
{@inheritdoc}
@return PromiseInterface
|
entailment
|
public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription)
{
// set default values
$fieldDescription->setAdmin($admin);
if ($admin->getModelManager()->hasMetadata($admin->getClass())) {
$metadata = $admin->getModelManager()->getMetadata($admin->getClass());
// set the default field mapping
if (isset($metadata->mappings[$fieldDescription->getName()])) {
$fieldDescription->setFieldMapping($metadata->mappings[$fieldDescription->getName()]);
if ('string' == $metadata->mappings[$fieldDescription->getName()]['type']) {
$fieldDescription->setOption('global_search', $fieldDescription->getOption('global_search', true)); // always search on string field only
}
}
// set the default association mapping
if (isset($metadata->associationMappings[$fieldDescription->getName()])) {
$fieldDescription->setAssociationMapping($metadata->associationMappings[$fieldDescription->getName()]);
}
}
$fieldDescription->setOption('code', $fieldDescription->getOption('code', $fieldDescription->getName()));
$fieldDescription->setOption('name', $fieldDescription->getOption('name', $fieldDescription->getName()));
}
|
{@inheritdoc}
|
entailment
|
public function getBaseDatagrid(AdminInterface $admin, array $values = [])
{
$defaultOptions = [];
if ($this->csrfTokenEnabled) {
$defaultOptions['csrf_protection'] = false;
}
$formBuilder = $this->formFactory->createNamedBuilder(
'filter',
'Symfony\Component\Form\Extension\Core\Type\FormType',
[],
$defaultOptions
);
return new Datagrid($admin->createQuery(), $admin->getList(), $this->getPager(), $formBuilder, $values);
}
|
{@inheritdoc}
|
entailment
|
public function buildForm(FormBuilderInterface $builder, array $options)
{
if ('doctrine_phpcr' != $options['sonata_field_description']->getAdmin()->getManagerType() || !$options['sonata_field_description']->getOption('sortable')) {
return;
}
$listener = new CollectionOrderListener($options['sonata_field_description']->getName());
$builder->addEventListener(FormEvents::SUBMIT, [$listener, 'onSubmit']);
}
|
{@inheritdoc}
|
entailment
|
public function treeAction(Request $request)
{
$root = $request->attributes->get('root');
return $this->render($this->template, [
'root_node' => $root,
'routing_defaults' => $this->treeConfiguration['routing_defaults'],
'repository_name' => $this->treeConfiguration['repository_name'],
'reorder' => $this->treeConfiguration['reorder'],
'move' => $this->treeConfiguration['move'],
'sortable_by' => $this->treeConfiguration['sortable_by'],
]);
}
|
Renders a tree, passing the routes for each of the admin types (document types)
to the view.
@param Request $request
@return Response
|
entailment
|
public function reorderAction(Request $request)
{
$parentPath = $request->get('parent');
$dropedAtPath = $request->get('dropped');
$targetPath = $request->get('target');
$position = $request->get('position');
if (null === $parentPath || null === $dropedAtPath || null === $targetPath) {
return new JsonResponse(['Parameters parent, dropped and target has to be set to reorder.'], Response::HTTP_BAD_REQUEST);
}
if (\in_array($position, ['over', 'child'])) {
return new JsonResponse(['Can not reorder when dropping into a collection.'], Response::HTTP_BAD_REQUEST);
}
$before = 'before' == $position;
$parentNode = $this->session->getNode($parentPath);
$targetName = PathHelper::getNodeName($targetPath);
if (!$before) {
$nodesIterator = $parentNode->getNodes();
$nodesIterator->rewind();
while ($nodesIterator->valid()) {
if ($nodesIterator->key() == $targetName) {
break;
}
$nodesIterator->next();
}
$targetName = null;
if ($nodesIterator->valid()) {
$nodesIterator->next();
if ($nodesIterator->valid()) {
$targetName = $nodesIterator->key();
}
}
}
$parentNode->orderBefore($targetName, PathHelper::getNodeName($dropedAtPath));
$this->session->save();
return new Response('', Response::HTTP_NO_CONTENT);
}
|
Reorder $moved (child of $parent) before or after $target.
@param Request $request
@return Response
|
entailment
|
public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription)
{
if ('_action' == $fieldDescription->getName() || 'actions' === $fieldDescription->getType()) {
$this->buildActionFieldDescription($fieldDescription);
}
$fieldDescription->setAdmin($admin);
$metadata = null;
if ($admin->getModelManager()->hasMetadata($admin->getClass())) {
/** @var ClassMetadata $metadata */
$metadata = $admin->getModelManager()->getMetadata($admin->getClass());
// TODO sort on parent associations or node name
$defaultSortable = true;
if ($metadata->hasAssociation($fieldDescription->getName())
|| $metadata->nodename === $fieldDescription->getName()
) {
$defaultSortable = false;
}
// TODO get and set parent association mappings, see
// https://github.com/sonata-project/SonataDoctrinePhpcrAdminBundle/issues/106
//$fieldDescription->setParentAssociationMappings($parentAssociationMappings);
// set the default field mapping
if (isset($metadata->mappings[$fieldDescription->getName()])) {
$fieldDescription->setFieldMapping($metadata->mappings[$fieldDescription->getName()]);
if (false !== $fieldDescription->getOption('sortable')) {
$fieldDescription->setOption(
'sortable',
$fieldDescription->getOption('sortable', $defaultSortable)
);
$fieldDescription->setOption(
'sort_parent_association_mappings',
$fieldDescription->getOption(
'sort_parent_association_mappings',
$fieldDescription->getParentAssociationMappings()
)
);
$fieldDescription->setOption(
'sort_field_mapping',
$fieldDescription->getOption(
'sort_field_mapping',
$fieldDescription->getFieldMapping()
)
);
}
}
// set the default association mapping
if (isset($metadata->associationMappings[$fieldDescription->getName()])) {
$fieldDescription->setAssociationMapping($metadata->associationMappings[$fieldDescription->getName()]);
}
$fieldDescription->setOption(
'_sort_order',
$fieldDescription->getOption('_sort_order', 'ASC')
);
}
if (!$fieldDescription->getType()) {
throw new \RuntimeException(sprintf(
'Please define a type for field `%s` in `%s`',
$fieldDescription->getName(),
\get_class($admin)
));
}
$fieldDescription->setOption(
'code',
$fieldDescription->getOption('code', $fieldDescription->getName())
);
$fieldDescription->setOption(
'label',
$fieldDescription->getOption('label', $fieldDescription->getName())
);
if (!$fieldDescription->getTemplate()) {
$fieldDescription->setTemplate($this->getTemplate($fieldDescription->getType()));
if (ClassMetadata::MANY_TO_ONE == $fieldDescription->getMappingType()) {
$fieldDescription->setTemplate('@SonataAdmin/CRUD/Association/list_many_to_one.html.twig');
}
if (ClassMetadata::MANY_TO_MANY == $fieldDescription->getMappingType()) {
$fieldDescription->setTemplate('@SonataAdmin/CRUD/Association/list_many_to_many.html.twig');
}
if ('child' == $fieldDescription->getMappingType() || 'parent' == $fieldDescription->getMappingType()) {
$fieldDescription->setTemplate('@SonataAdmin/CRUD/Association/list_one_to_one.html.twig');
}
if ('children' == $fieldDescription->getMappingType() || 'referrers' == $fieldDescription->getMappingType()) {
$fieldDescription->setTemplate('@SonataAdmin/CRUD/Association/list_one_to_many.html.twig');
}
}
$mappingTypes = [
ClassMetadata::MANY_TO_ONE,
ClassMetadata::MANY_TO_MANY,
'children',
'child',
'parent',
'referrers',
];
if ($metadata
&& $metadata->hasAssociation($fieldDescription->getName())
&& \in_array($fieldDescription->getMappingType(), $mappingTypes, true)
) {
$admin->attachAdminClass($fieldDescription);
}
}
|
{@inheritdoc}
@throws \RuntimeException if the $fieldDescription does not have a type
|
entailment
|
public function filter(ProxyQueryInterface $proxyQuery, $alias, $field, $data)
{
if (!$data || !\is_array($data) || !\array_key_exists('type', $data) || !\array_key_exists('value', $data)) {
return;
}
$values = (array) $data['value'];
$type = $data['type'];
// clean values
foreach ($values as $key => $value) {
$value = trim((string) $value);
if (!$value) {
unset($values[$key]);
} else {
$values[$key] = $value;
}
}
// if values not set or "all" specified, do not do this filter
if (!$values || \in_array('all', $values, true)) {
return;
}
$andX = $this->getWhere($proxyQuery)->andX();
foreach ($values as $value) {
if (ChoiceType::TYPE_NOT_CONTAINS == $type) {
$andX->not()->like()->field('a.'.$field)->literal('%'.$value.'%');
} elseif (ChoiceType::TYPE_CONTAINS == $type) {
$andX->like()->field('a.'.$field)->literal('%'.$value.'%');
} elseif (ChoiceType::TYPE_EQUAL == $type) {
$andX->like()->field('a.'.$field)->literal($value);
}
}
// filter is active as we have now modified the query
$this->active = true;
}
|
{@inheritdoc}
|
entailment
|
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('sonata.admin.pool')) {
return;
}
$this->addAssetsToAdminPool($container->findDefinition('sonata.admin.pool'));
$this->addFormResources($container);
}
|
{@inheritdoc}
|
entailment
|
public function guessType($class, $property, ModelManagerInterface $modelManager)
{
if (!$metadata = $this->getMetadata($class)) {
return new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE);
}
if ($metadata->hasAssociation($property)) {
$mapping = $metadata->mappings[$property];
switch ($mapping['type']) {
case ClassMetadata::MANY_TO_MANY:
case 'referrers':
return new TypeGuess('doctrine_phpcr_many_to_many', [], Guess::HIGH_CONFIDENCE);
case ClassMetadata::MANY_TO_ONE:
case 'parent':
return new TypeGuess('doctrine_phpcr_many_to_one', [], Guess::HIGH_CONFIDENCE);
case 'children':
return new TypeGuess('doctrine_phpcr_one_to_many', [], Guess::HIGH_CONFIDENCE);
case 'child':
return new TypeGuess('doctrine_phpcr_one_to_one', [], Guess::HIGH_CONFIDENCE);
}
}
// TODO: missing multivalue support
switch ($metadata->getTypeOfField($property)) {
case 'boolean':
return new TypeGuess(BooleanType::class, [], Guess::HIGH_CONFIDENCE);
case 'date':
return new TypeGuess(DatePickerType::class, [], Guess::HIGH_CONFIDENCE);
case 'decimal':
case 'double':
return new TypeGuess(TextType::class, [], Guess::MEDIUM_CONFIDENCE);
case 'integer':
case 'long':
return new TypeGuess(NumberType::class, [], Guess::MEDIUM_CONFIDENCE);
case 'string':
return new TypeGuess(TextType::class, [], Guess::HIGH_CONFIDENCE);
case 'binary':
case 'uri':
return new TypeGuess(TextType::class, [], Guess::MEDIUM_CONFIDENCE);
}
return new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE);
}
|
{@inheritdoc}
|
entailment
|
public function build(CommandInterface $command)
{
$uri = sprintf('%s/%s/%s/%s',
rtrim($this->getBaseUrl()),
$command->getInterface(),
$command->getMethod(),
$command->getVersion()
);
return new Uri($uri);
}
|
{@inheritdoc}
|
entailment
|
public function filter(ProxyQueryInterface $proxyQuery, $alias, $field, $data)
{
if (!\is_callable($this->getOption('callback'))) {
throw new \RuntimeException(sprintf('Please provide a valid callback for option "callback" and field "%s"', $this->getName()));
}
$this->active = true === \call_user_func($this->getOption('callback'), $proxyQuery, $alias, $field, $data);
}
|
{@inheritdoc}
@throws \InvalidArgumentException if the filter is not configured with a
callable in the 'callback' option field
|
entailment
|
public function filter(ProxyQueryInterface $proxyQuery, $alias, $field, $data)
{
if (!$data || !\is_array($data) || !\array_key_exists('type', $data) || !\array_key_exists('value', $data)) {
return;
}
if (\is_array($data['value']) || !\in_array($data['value'], [BooleanType::TYPE_NO, BooleanType::TYPE_YES], true)) {
return;
}
$where = $this->getWhere($proxyQuery);
$where->eq()->field('a.'.$field)->literal(BooleanType::TYPE_YES == $data['value'] ? true : false);
// filter is active as we have now modified the query
$this->active = true;
}
|
{@inheritdoc}
|
entailment
|
public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription)
{
$fieldDescription->setAdmin($admin);
$metadata = null;
if ($admin->getModelManager()->hasMetadata($admin->getClass())) {
/** @var ClassMetadata $metadata */
$metadata = $admin->getModelManager()->getMetadata($admin->getClass());
// set the default field mapping
if (isset($metadata->mappings[$fieldDescription->getName()])) {
$fieldDescription->setFieldMapping($metadata->mappings[$fieldDescription->getName()]);
}
// set the default association mapping
if ($metadata->hasAssociation($fieldDescription->getName())) {
$fieldDescription->setAssociationMapping($metadata->getAssociation($fieldDescription->getName()));
}
}
if (!$fieldDescription->getType()) {
throw new \RuntimeException(sprintf('Please define a type for field `%s` in `%s`', $fieldDescription->getName(), \get_class($admin)));
}
$fieldDescription->setOption('code', $fieldDescription->getOption('code', $fieldDescription->getName()));
$fieldDescription->setOption('label', $fieldDescription->getOption('label', $fieldDescription->getName()));
if (!$fieldDescription->getTemplate()) {
$fieldDescription->setTemplate($this->getTemplate($fieldDescription->getType()));
if (ClassMetadata::MANY_TO_ONE == $fieldDescription->getMappingType()) {
$fieldDescription->setTemplate('@SonataAdmin/CRUD/Association/show_many_to_one.html.twig');
}
if (ClassMetadata::MANY_TO_MANY == $fieldDescription->getMappingType()) {
$fieldDescription->setTemplate('@SonataAdmin/CRUD/Association/show_many_to_many.html.twig');
}
}
$mappingTypes = [
ClassMetadata::MANY_TO_ONE,
ClassMetadata::MANY_TO_MANY,
'children',
'child',
'parent',
'referrers',
];
if ($metadata && $metadata->hasAssociation($fieldDescription->getName()) && \in_array($fieldDescription->getMappingType(), $mappingTypes, true)) {
$admin->attachAdminClass($fieldDescription);
}
}
|
The method defines the correct default settings for the provided FieldDescription.
{@inheritdoc}
@throws \RuntimeException if the $fieldDescription does not have a type
|
entailment
|
public function filter(ProxyQueryInterface $proxyQuery, $alias, $field, $data)
{
if (!$data || !\is_array($data) || !\array_key_exists('value', $data) || !is_numeric($data['value'])) {
return;
}
$type = $data['type'] ?? false;
$where = $this->getWhere($proxyQuery);
$value = $data['value'];
switch ($type) {
case NumberType::TYPE_GREATER_EQUAL:
$where->gte()->field('a.'.$field)->literal($value);
break;
case NumberType::TYPE_GREATER_THAN:
$where->gt()->field('a.'.$field)->literal($value);
break;
case NumberType::TYPE_LESS_EQUAL:
$where->lte()->field('a.'.$field)->literal($value);
break;
case NumberType::TYPE_LESS_THAN:
$where->lt()->field('a.'.$field)->literal($value);
break;
case NumberType::TYPE_EQUAL:
default:
$where->eq()->field('a.'.$field)->literal($value);
}
// filter is active as we have now modified the query
$this->active = true;
}
|
{@inheritdoc}
|
entailment
|
public function guessType($class, $property, ModelManagerInterface $modelManager)
{
if (!$metadata = $this->getMetadata($class)) {
return false;
}
$options = [
'field_type' => TextType::class,
'field_options' => [],
'options' => [],
];
if ($metadata->hasAssociation($property)) {
// TODO add support for children, child, referrers and parentDocument associations
$mapping = $metadata->mappings[$property];
$options['operator_type'] = BooleanType::class;
$options['operator_options'] = [];
$options['field_type'] = DocumentType::class;
if (!empty($mapping['targetDocument'])) {
$options['field_options'] = [
'class' => $mapping['targetDocument'],
];
}
$options['field_name'] = $mapping['fieldName'];
$options['mapping_type'] = $mapping['type'];
switch ($mapping['type']) {
case ClassMetadata::MANY_TO_MANY:
return new TypeGuess('doctrine_phpcr_many_to_many', $options, Guess::HIGH_CONFIDENCE);
case ClassMetadata::MANY_TO_ONE:
return new TypeGuess('doctrine_phpcr_many_to_one', $options, Guess::HIGH_CONFIDENCE);
}
}
// TODO add support for node, nodename, version created, version name
$options['field_name'] = $property;
switch ($metadata->getTypeOfField($property)) {
case 'boolean':
$options['field_type'] = BooleanType::class;
$options['field_options'] = [];
return new TypeGuess(BooleanFilter::class, $options, Guess::HIGH_CONFIDENCE);
case 'date':
return new TypeGuess(DateFilter::class, $options, Guess::HIGH_CONFIDENCE);
case 'decimal':
case 'float':
return new TypeGuess(NumberFilter::class, $options, Guess::HIGH_CONFIDENCE);
case 'integer':
$options['field_type'] = NumberType::class;
$options['field_options'] = [
'csrf_protection' => false,
];
return new TypeGuess(NumberFilter::class, $options, Guess::HIGH_CONFIDENCE);
case 'text':
case 'string':
$options['field_type'] = TextType::class;
return new TypeGuess(StringFilter::class, $options, Guess::HIGH_CONFIDENCE);
}
return new TypeGuess(StringFilter::class, $options, Guess::LOW_CONFIDENCE);
}
|
{@inheritdoc}
|
entailment
|
public function buildForm(FormBuilderInterface $builder, array $options)
{
$choices = [
$this->translator->trans('label_type_contains', [], 'SonataAdminBundle') => self::TYPE_CONTAINS,
$this->translator->trans('label_type_not_contains', [], 'SonataAdminBundle') => self::TYPE_NOT_CONTAINS,
$this->translator->trans('label_type_equals', [], 'SonataAdminBundle') => self::TYPE_EQUAL,
$this->translator->trans('label_type_contains_words', [], 'SonataDoctrinePHPCRAdmin') => self::TYPE_CONTAINS_WORDS,
];
$builder
->add('type', SymfonyChoiceType::class, [
'choices' => $choices,
'required' => false,
])
->add('value', $options['field_type'], array_merge(['required' => false], $options['field_options']))
;
}
|
{@inheritdoc}
|
entailment
|
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('sonata_doctrine_phpcr_admin');
// Keep compatibility with symfony/config < 4.2
if (!method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->root('sonata_doctrine_phpcr_admin');
} else {
$rootNode = $treeBuilder->getRootNode();
}
$rootNode
->fixXmlConfig('template')
->children()
->arrayNode('templates')
->children()
->arrayNode('form')
->prototype('scalar')->end()
->defaultValue(['@SonataDoctrinePHPCRAdmin/Form/form_admin_fields.html.twig'])
->end()
->arrayNode('filter')
->prototype('scalar')->end()
->defaultValue(['@SonataDoctrinePHPCRAdmin/Form/filter_admin_fields.html.twig'])
->end()
->arrayNode('types')
->children()
->arrayNode('list')
->useAttributeAsKey('name')
->prototype('scalar')->end()
->end()
->arrayNode('show')
->useAttributeAsKey('name')
->prototype('scalar')->end()
->end()
->end()
->end()
->scalarNode('pager_results')->defaultValue('@SonataDoctrinePHPCRAdmin/Pager/simple_pager_results.html.twig')->cannotBeEmpty()->end()
->end()
->end()
->arrayNode('document_tree')
->addDefaultsIfNotSet()
->canBeEnabled()
->children()
->scalarNode('repository_name')
->defaultNull()
->info('The repository name the resource API connects to.')
->end()
->arrayNode('routing_defaults')
->prototype('scalar')->end()
->info('Routing defaults passed to the resources API call.')
->end()
->scalarNode('sortable_by')
->defaultValue('position')
->info('Defines by which property to sort sibling documents.')
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
|
Generates the configuration tree.
@return TreeBuilder
|
entailment
|
public function init()
{
if (!$this->getQuery()) {
throw new \RuntimeException('Uninitialized QueryBuilder');
}
$this->resetIterator();
$this->setNbResults($this->computeNbResult());
if (0 == $this->getPage() || 0 == $this->getMaxPerPage() || 0 == $this->getNbResults()) {
$this->setLastPage(0);
$this->getQuery()->setFirstResult(0);
$this->getQuery()->setMaxResults(0);
} else {
$offset = ($this->getPage() - 1) * $this->getMaxPerPage();
$this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
$this->getQuery()->setFirstResult($offset);
$this->getQuery()->setMaxResults($this->getMaxPerPage());
}
}
|
Initializes the pager setting the offset and maxResults in ProxyQuery
and obtaining the total number of pages.
@throws \RuntimeException the QueryBuilder is uninitialized
|
entailment
|
public function update($object)
{
try {
$this->dm->persist($object);
$this->dm->flush();
} catch (\Exception $e) {
throw new ModelManagerException('', 0, $e);
}
}
|
{@inheritdoc}
@throws ModelManagerException if the document manager throws any exception
|
entailment
|
public function delete($object)
{
try {
$this->dm->remove($object);
$this->dm->flush();
} catch (\Exception $e) {
throw new ModelManagerException('', 0, $e);
}
}
|
{@inheritdoc}
@throws ModelManagerException if the document manager throws any exception
|
entailment
|
public function find($class, $id)
{
if (!isset($id)) {
return;
}
if (null === $class) {
return $this->dm->find(null, $id);
}
return $this->dm->getRepository($class)->find($id);
}
|
Find one object from the given class repository.
{@inheritdoc}
|
entailment
|
public function getNewFieldDescriptionInstance($class, $name, array $options = [])
{
if (!\is_string($name)) {
throw new \RunTimeException('The name argument must be a string');
}
$metadata = $this->getMetadata($class);
$fieldDescription = new FieldDescription();
$fieldDescription->setName($name);
$fieldDescription->setOptions($options);
if (isset($metadata->associationMappings[$name])) {
$fieldDescription->setAssociationMapping($metadata->associationMappings[$name]);
}
if (isset($metadata->fieldMappings[$name])) {
$fieldDescription->setFieldMapping($metadata->fieldMappings[$name]);
}
return $fieldDescription;
}
|
{@inheritdoc}
@throws \RunTimeException if $name is not a string
@return FieldDescription
|
entailment
|
public function createQuery($class, $alias = 'a')
{
$qb = $this->getDocumentManager()->createQueryBuilder();
$qb->from()->document($class, $alias);
return new ProxyQuery($qb, $alias);
}
|
@param string $class the fully qualified class name to search for
@param string $alias alias to use for this class when accessing fields,
defaults to 'a'
@throws \InvalidArgumentException if alias is not a string or an empty string
@return ProxyQueryInterface
|
entailment
|
public function getIdentifierValues($document)
{
$class = $this->getMetadata(ClassUtils::getClass($document));
$path = $class->reflFields[$class->identifier]->getValue($document);
return [$path];
}
|
Transforms the document into the PHPCR path.
Note: This is returning an array because Doctrine ORM for example can
have multiple identifiers, e.g. if the primary key is composed of
several columns. We only ever have one, but return that wrapped into an
array to adhere to the interface.
{@inheritdoc}
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.