Command works in mongodb compass but not in php - php

_id:1
email:"j#g.com"
This is my collection. When I write
{ email: /^J/i }
in compass it works absolutely fine, but in php
$user_collection->find(
["email" => ['$regex' => "/^j/i"]]
);
finds nothing

In your example /^J/i, the i is an option flag to request case-insensitive search.
When using $regex you need to use a separate options field:
['$regex' => "^j", '$options'=>"i"]

Related

How to auto format PHP code curly braces to new lines in VS Code

I'm currently using VS Code's latest version 1.41.1 (at the time of writing).
I've installed PHP CS Fixer to auto-format my code. However there's a behavious that I don't like. It always formats the code like this:
if (condition) {
// code...
} else {
// code
}
But this is not giving me good readability.
I'd like to achieve this:
if (condition)
{
// code...
}
else
{
// code
}
Is there any extentsion that supports this code formatting for PHP in VS Code? Or is there any option in PHP CS Fixer to skip formatting these curly brackets? Any other otpions?
Based on #Nicolas's comment I was able to make it work in 2 steps.
I had to create a file in the root of my project with a name of .php_cs
Add this block of code to the file:
<?php
return PhpCsFixer\Config::create()
->setRules(array(
'braces' => array(
'position_after_anonymous_constructs' => 'next',
'position_after_control_structures' => 'next',
)
));
All done and works like a charm. Thanks for the help #Nicolas!
Was looking for the same thing. I tried the (accepted) answer Radical_activity gave, but that didn't work for me. Found this another snippets here:
https://stackoverflow.com/a/54883745/4638682
Snippet:
<?php
$finder = PhpCsFixer\Finder::create()
//->exclude('somedir')
//->notPath('src/Symfony/Component/Translation/Tests/fixtures/resources.php'
->in(__DIR__)
;
return PhpCsFixer\Config::create()
->setRules([
'#PSR2' => true,
'strict_param' => false,
'array_syntax' => ['syntax' => 'long'],
'braces' => [
'allow_single_line_closure' => true,
'position_after_functions_and_oop_constructs' => 'same'],
])
->setFinder($finder)
;
From which you also need to create a .php_cs file in your repository.
That worked for me!

Yii2 translating data stored in database

I'm working with Yii2 Framework, and already configured i18n component using this guide:
http://thecodeninja.net/2014/12/i18n-with-yii-2-advanced-template/
So, I can now translate strings within my php files using Yii::t() function. Translatable strings are extracted using $ ./yii message/extract console command, which generates proper translation files.
I now need to display translations for strings stored in the database.
I could use Yii:t() with a variable instead of a string as an argument like this
echo Yii:t('app', $some_string_from_db );
and make a new php file with some code like this
<?php
function dbStringsToTranslate() {
$o = Yii::t('app','db english string 1');
$o.= Yii::t('app','db english string 2');
$o.= Yii::t('app','db english string 3');
return $o;
}
This way $ ./yii message/extract command will find the needed translations.
This is working Ok, but of course $ ./yii message/extract is throwing some warnings anywhere I use Yii:t() with variables.
Skipping line 39. Make sure both category and message are static strings.
I think this is not a big deal, but well, here is my question:
Is this a right way to translate strings stored in a database?
Is there a better way to accomplish this?
You can check out this extension. https://github.com/creocoder/yii2-translateable it allows for attaching behaviors to models to support multiple languages.
I am using it now in a projects and it is easy to use.
I was having the same problem, and I found the solution with this module. In the module configuration you have the 'tables' array, in which you can specify which field(s) of which table(s) should be translated.
Then, the module has its own 'scan' action (equivalent to message/extract) with which it adds all the translatable strings to database (using DbMessageSource): all Yii::t, the specified database fields, and many more (even javascript, check the docs). It also has a nice user interface to do the translations, it's awesome!
For example, with the following configuration the field name from table nationality will be scanned and added for its translation (i.e country names):
'modules' => [
'translatemanager' => [
'class' => 'lajax\translatemanager\Module',
...
'tables' => [ // Properties of individual tables
[
'connection' => 'db', // connection identifier
'table' => 'nationality', // table name
'columns' => ['name'], // names of multilingual fields
'category' => 'database-table-name',// the category is the database table name
'categoryPrefix' => 'lx-' //
]
]
],
],
You can generate php file with some fake Yii:t() calls.
For example:
$filename = Yii::getAlias('#frontend/runtime/fake-category-translations.php');
$str = '<?php' . PHP_EOL;
foreach (Category::find()->all() as $category) {
$str .= "Yii::t('category', '{$category->name}');" . PHP_EOL;
}
file_put_contents($filename, $str);
In output this file will be something like this:
<?php
Yii::t('category', 'Art & Design');
Yii::t('category', 'Creativity');
Yii::t('category', 'Educational');
Yii::t('category', 'Education');
Yii::t('category', 'Lifestyle');
Yii::t('category', 'Casual');
So, now you can just call console method for searching untranslated strings:
php yii message/extract #frontend/messages/config.php
I know this is old but I faced same thing with rest API, and here is how I went about resolving it. Note that When saving I used
$post->comment = Yii::t('app', 'My Nice Comment here');
$post->save();
class Post extends ActiveRecord
{
public function fields()
{
$fields = parent::fields();
$fields['comment'] = function ($model) {
return Yii::t('app', $model->comment);
};
return $fields;
}
}

exception: can't temprelease nested lock

I am trying to run some server-side JS in Mongo. Operations I am trying to perform are:
db.dropDatabase(); // removing current database
db.copyDatabase('db_dump', 'db', 'localhost'); // substituting it with a dump
Everything works perfectly nice. When I am storing this as a function:
function () {
db.dropDatabase();
return db.copyDatabase('db_dump', 'db', 'localhost');
}
and executing it, everything is also nice and returns me {"ok" : 1}
But when I try to execute this using php driver:
$db->execute("function(){ db.dropDatabase(); return db.copyDatabase('db_dump', 'db', 'localhost'); }");
I get
{
"retval": {
"errmsg":"exception: can't temprelease nested lock",
"code":10298,
"ok":0
},
"ok":1
}
My first though was that I just need to get out of the lock, so I tried this
$db->command(
array(
'$eval' => "function() { db.dropDatabase(); return db.copyDatabase('db_dump', 'db', 'localhost');}"
),
array(
'nolock'=> true
)
);
Nothing else is using database at this point.
Any ideas how to get rid of this error?
I am using Mongo 2.4.4, PHP 5.3.13 and driver 1.2.10
P.S. Tried this on PHP 5.4.16 and the situation is the same
This command cannot be invoked through the eval command (see this thread for some additional discussion on the matter). Rather than use JS methods, you can invoke the copydb command directly with MongoDB::command(). The following script will copy between two databases on the same server, since I omitted the fromhost option:
$m = new MongoClient();
$m->a->drop();
$m->admin->command([
'copydb' => 1,
'fromdb' => 'b',
'todb' => 'a',
]);

SugarCRM REST API set_relationship between Quote and ProductBundles

I am using SugarCRM Pro 6.5.5
I need to create a Quote and add Products to it with the REST API. All bundles > Prof the set_entry's work, and the set_relationship for ProductBoducts works fine. But, set_relationship for Quotes > ProductBundles does not work.
Here is my input for ProductBundles > Products: this works fine
{
"session":"5qklti658f0ooou135vt8fkbi4",
"module":"ProductBundles",
"module_id":"50b71673-b555-9d68-04c9-508ef9582f47",
"link_field_name":"products",
"related_ids":[
"a9615ab1-cd89-1549-f9b8-508f00c6fa84"
]
}
Here is my input for Quotes > ProductBundles: this does not work
{
"session":"jqodi1pu8u2l8basca1hhcbt27",
"module":"Quotes",
"module_id":"bc01a88a-35c9-25ed-dfac-508ef206a264",
"link_field_name":"product_bundles",
"related_ids":[
"50b71673-b555-9d68-04c9-508ef9582f47"
]
}
BUT it still returns:
{
"created":1,
"failed":0,
"deleted":0
}
But, no record is created in the product_bundle_quote table.
I have dug into the Sugar code a little, and found something interesting.
In service/core/SoapHelperWebService.php on line 735, is this:
$mod->$link_field_name->add($related_ids, $name_value_pair);
Which calls the add method in file data/Relationships/M2MRelationship.php on line 118. Interestingly, $lhsLinkName is NULL, which causes the method to return false. Here is a snippet:
public function add($lhs, $rhs, $additionalFields = array())
{
$lhsLinkName = $this->lhsLink;
$rhsLinkName = $this->rhsLink;
if (empty($lhs->$lhsLinkName) && !$lhs->load_relationship($lhsLinkName))
{
$lhsClass = get_class($lhs);
$GLOBALS['log']->fatal("could not load LHS $lhsLinkName in $lhsClass");
return false;
}
if (empty($rhs->$rhsLinkName) && !$rhs->load_relationship($rhsLinkName))
{
$rhsClass = get_class($rhs);
$GLOBALS['log']->fatal("could not load RHS $rhsLinkName in $rhsClass");
return false;
}
It returns FALSE in the first if() block, which means the record is never created.
Also, this shows up in my log:
[2139][1][FATAL] could not load LHS in ProductBundle
So yeah, I'm stuck here. I tried searching for everything I could, including the error, but I haven't found anything helpful.
This is a Sugar bug, which will be fixed in the 6.7 release. In the meantime, check out this forums post for the code fix.
http://forums.sugarcrm.com/f6/create-quote-line-items-web-service-api-83183/
This does turn out to be a Sugar Bug, but not the one in the other answer. It's actually related to this bug: Bug 32064. They were able to provide me with a custom module that I could upload and activate to address the issue before release 6.7 when this is slated to be addressed officially. You'll probably want to contact SugarCRM directly for this workaround, depending on your time frame.
I was having the same issue and in order to resolve that i added the below mentioned code in product bundles vardef and it's start working fine.
'quotes' =>
array (
'name' => 'quotes',
'type' => 'link',
'vname'=>'LBL_PRODUCT_BUNDLES',
'relationship' => 'product_bundle_quote',
'source'=>'non-db',
),
Thanks!
You have to link the quote to products too.
make sure in your quote vardef there's the following:
'products' =>
array (
'name' => 'products',
'type' => 'link',
'relationship' => 'quote_products',
'vname' => 'LBL_PRODUCTS',
'source'=>'non-db',
),
and in your webservice, set the relationship between quote and products
{
"session":$session_id,
"module":"Quotes",
"module_id":$quote_id,
"link_field_name":"products",
"related_ids":[
$product_id
]
}
It works for me.

Using PHP to syntax highlight all <code>s on a page... ($highlight_string() isn't an option)

I'm using CodeIgniter, alongside the highlight_code("$string"); (More info) function to provide syntax highlighting to a dynamic site. I want the users to be able to submit their own posts written in a BBCode-style format. I'm using NBBC PHP library for this.
My problem is that nomatter how I do it I cannot get NBBC to syntax-highlight only [code][/code] tags that my users enter. Here's the PHP for [code]:
'code' => Array(
'mode' => BBCODE_MODE_ENHANCED,
'template' => "\n<div class=\"bbcode_code\">\n<p>Code:</p>\n<code><?php $highlight_code(\"?>{\$_content/v}<?php \");?></code>\n</div>\n",
'class' => 'code',
'allow_in' => Array('listitem', 'block', 'columns'),
'content' => BBCODE_VERBATIM,
'before_tag' => "sns",
'after_tag' => "sn",
'before_endtag' => "sn",
'after_endtag' => "sns",
'plain_start' => "<div id=\"footer\">",
'plain_end' => "</div>",
'simple_start' => '\n<div class=\"bbcode_code\">\n<p>Code:</p>\n<code>',
'simple_end' => '</code>\n</div>\n',
),
If you see the line which says <?php $highlight_code(\"?>{\$_content/v}<?php \");?> that I whacked in there, I thought that would highlight the code contained within the tags. I can't quite remember what this outputs (I've tried plenty of different combinations) but the closest I got was it being exported as text from PHP - in my page XHTML source it just appeared as text.
What can I do to make all content within tags on a page be syntax-highlighted, ideally using highlight_code($string); or similar?
I was thinking preg_replace would be an option but I don't know how to do it to dynamically replace everything between outputted tags (not [code], remember, but HTML which NBBC outputs).
First use preg_match to extract the contents of the [code][/code] tags, and highlight_code() that.
Use the results to preg_replace() the code area in the original string with the highlighted code. Pseudocode-ish:
$code = preg_match(/code pattern/, $string);
$code = highlight_code($code);
$string = preg_replace(/code pattern/, $code, $string);
Hope it works.

Categories