PHP streamline add and remove array element - php

Is there a way in PHP or Laravel 5.2 to streamline the following:
iterate through array. In my example, a collection of industries
add an item. In my example In my example, 'app_id' and padded uuid
remove original item. In my case the original uuid element
Ideal Outcome:
Can I streamline function paddUuids($item) and public function getIndustries()
Context (why do I want to do this):
Using native uuid with CSS doesn't work as class and ID because the first character cannot be numeric so I need to add alpha prefix to uuid. Second, Angular 1.5 seems to struggles with Uuid (even as string) or Uuid with hyphens i.e. keep getting duplicate index error.
class SegmentsController extends Controller
{
use UuidTrait;
/**
* #var Industry
*/
protected $industry;
/**
* SegmentsController constructor.
*/
public function __construct(Industry $industry)
{
$this->industry = $industry;
}
/**
* Remove uuid hypens and add prefix to use with Angular and as CSS class
* #param $item
* #return mixed
*/
function paddUuids($item)
{
$item['app_id'] = $this->paddUuid($item['uuid']);
unset($item['uuid']);
return $item;
}
/**
* Return Iterate through industries
* #return array
*/
public function getIndustries()
{
return array_map (array($this, 'paddUuids'), $this->industry->get()->toArray() );
}
}

Related

Laravel Scout - searchableAs index

I have a Thread that I am indexing to Algolia and i want to be able to only allow user to search by the title and body of the thread.
So in my thread model:
/**
* Get the index name for the model.
*
* #return string
*/
public function searchableAs()
{
return 'title';
}
/**
* Get the indexable data array for the model.
*
* #return array
*/
public function toSearchableArray()
{
$array = $this->toArray();
// Customize array...
unset($array['created_at'],$array['updated_at']);
return $array;
}
So the first method is to index a specific column of the thread table and the second method is to choose which columns to place it in algolia.
I guess my question is what is searchableAs() for as I am confused with the explanation by the doc?

Change Entity assert constrains dynamically without FormType

So the problem is like this:
I am trying to save some data from API and I need to validate them with Symfony validation ex:
private $id;
/**
* #var
* #Assert\Length(max="255")
* #CustomAssert\OrderExternalCode()
* #CustomAssert\OrderShipNoExternalCode()
*/
private $code;
private $someId;
/**
* #var
* #Assert\NotBlank()
* #Assert\Length(max="255")
*/
private $number;
this works well but now I need to add some Assert Constrains dynamically from the controller and that is where I am stuck!
Does anyone knows how to do that or any suggestion that might help?
Currently I did an extra constraint which does extra query in the DB and I don't want to do that and I am not using FormType.
You can use groups and use (or leave out) the extra group you're talking about.
Using the CallbackConstraint should help I think, in your case :
use My\Custom\MyConstraint;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
// This is not tested !
class MyEntity
{
/**
* #Assert\Callback()
*/
public function validateSomeId(ExecutionContextInterface $context)
{
$constraint = new MyConstraint(['code' => $this->code]);
$violations = $context->getValidator()->validate($this->number, $constraint);
foreach ($violations as $violation) {
$context->getViolations()->add($violation);
}
}
}
See https://symfony.com/doc/current/reference/constraints/Callback.html
EDIT : I don't know what you're trying to validate so I just put some random params of your entity in there
So I wanted to dynamically validate the request data based on a condition in the controller.
I specified an extra group for that in the entity like so:
/**
* #var
* #Assert\NotBlank(groups={"extra_check"})
* #Assert\Length(max="255")
*/
private $externalId;
Then in the controller I just did the condition to validate with the extra group or not.
$groups = $order->getExternalCode() != null ? ['Default'] : ['Default', 'extra_check'];
$this->validateRequest($request, null, $groups);
The Default group is the one without group specified and the other one is the group I specified in the field

How to PHPDoc a declarative array?

How i can create a PHPDoc block for an declarative array?.
For example, let's say that i have the next function:
/**
* #return ??????????
*/
function dummy() {
$x1=array("key1"=>"hello","ke2"=>"world");
return $x1;
}
// ... later
$x1=dummy();
echo $x1["key1"];
I want to be explicit in the array result, instead of use #return array.
(i also tried) I also know that i can return an array of object with #return Class[] but in this case, im not using classes.
Thanks.

PHPDoc - Different objects with different class within an array

Let's say that I have a function that returns array $data with a User object $user and a Car object $car
function my_function(){
return array(
new User(),
new Car()
);
}
What should I use for my #return parameter for the function documentation?
I Would do it this way
/**
* #return User[]|Car[]
*/
General | means or and SomeType[] means there is an array of SomeType
Are you Sure, you did not want this?
/**
* My Parent Object
*/
class SomeClass {
/**
* The User
* #var User
*/
public $User;
/**
* The Car
* #var Car
*/
public $Car;
}
The good (evil) thing about PHP is, you can mix array types. In a strong Typed Language (for reason) you can not. Here we use Interfaces and something like this. What we try with PHPDoc is to strong type PHP. So you should play the rules of a strong typed language.

Auto-completion for Zend Form Elements

When creating form elements with Zend (using Zend Studio for Eclipse), I'd like some auto completion or hints. Here's what I'm thinking. I'm sure these exist, but I don't know how to get them.
I type createElement and auto-completes gives me the signature createElement($type, $name). Great, I select it.
but when I try to set the $type I don't get any hints like DateTextBox or ValidationTextBox. Being new, I see how this can be useful. What do you do to remember all the options?
for the array of attributes like require, invalidMessage, I'd like to get a list of those to choose from, and/or auto-complete when I start typing one.
// Date field
$date = $this->createElement('DateTextBox', 'date',
array('require' => 'true', 'invalidMessage' => 'Invalid date format')
);
$date->setLabel('date')->setRequired(true);
You have few options to help yourself, without waiting for any plugin:
learn it and remember ;)
extend your phpDoc blocks with all available options:
Example (to be honest I don't know if Eclipse supports html in phpDoc or even any text after variable name in #param, but it works fine in Netbeans):
/**
* [...]
* #param string $type Can be: <ul><li>DateTextBox</li><li>ValidationTextBox</li></ul>
* #param string $name Whatever
* #param array|Zend_Config $options Array with following keys: <ul><li>require</li><li>invalidMessage</li></ul>
* #return Zend_Form_Element
*/
public function createElement($type, $name, $options = null)
extend Zend class and create your own methods to simplify your work
Example:
class My_Zend_Form_Element extends Zend_Form_Element
{
public function createDateTextBox($name, $options = null)
{
return $this->createElement('DateTextBox', $name, $options);
}
}
declare some well named constants and provide some hint in phpDoc
Example: (type ZFE_OPTIONS and IDE should show hint with some constants to use as array keys)
/**
* Can be true or false
*/
define('ZFE_OPTIONS_REQUIRE','require');
create your own helper classes with methods to produce valid options array
Example:
class ZFE_Options
{
protected $opts = array();
/**
* #param bool $req
* #return ZFE_Options
*/
public function setRequired($req){
$this->opts['require'] = (bool)$req;
return $this;
}
/**
* #param string $txt
* #return ZFE_Options
*/
public function setInvalidMessage($txt){
$this->opts['invalidMessage'] = (string)$txt;
return $this;
}
/**
* #return array
*/
public function toArray(){
return $this->opts;
}
}
$zfe_options = new ZFE_Options();
$opts = $zfe_options
->setRequired(true)
->setInvalidMessage('Please provide valid email address')
->toArray();
That's not possible. It's not how autocompletion works. The hints you get are taken directly from ZF's code documentation. Nothing more, nothing less. Everything you see as hints is taken directly from the DocBlock and method signature, e.g.
/**
* Create an element
*
* Acts as a factory for creating elements. Elements created with this
* method will not be attached to the form, but will contain element
* settings as specified in the form object (including plugin loader
* prefix paths, default decorators, etc.).
*
* #param string $type
* #param string $name
* #param array|Zend_Config $options
* #return Zend_Form_Element
*/
public function createElement($type, $name, $options = null)
Eclipse can tell you to insert a string or an array and it will know that the method returns a Zend_Form_Element, but it cannot tell you what these strings should be.
The only place where I know something like what you describe exists is for CSS files. For some reason, when I type in display: it will give me an autocomplete box with possible values for this declaration. If you want more sophisticated autocomplete like this, consider filing this as a feature request to Zend.

Categories