Let's say I have these classes:
Old_Class
New_Class
If this exists ->something(new Old_Class()) or Old_Class::staticMethod() or $oldClass->methodCall() I want a code sniff to warn "Old_Class usage found, recommend using New_Class instead".
I found this sniff Generic.PHP.ForbiddenFunctions but it only seems to catch built-in php functions is_array, is_null, etc.
Do I need to write a custom sniff for this?
If so, what token should I added to the register() function to catch on?
I couldn't use a built-in one. I had to write one using T_STRING.
public function register()
{
return [
T_STRING,
];
}
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$stackPtr]['content'] === 'Old_Class') {
$error = 'Old_Class usage found, consider using New_Class instead.';
$phpcsFile->addWarning($error, $stackPtr);
}
}
I know this is a fairly old question, but there are two possible solutions I'm aware of:
The Slevomat coding standard for Codesniffer includes a sniff to report usage of any of an array of forbidden classes
Static analysis tools are another approach for this. If you mark a class with the #deprecated annotation, I know from personal experience that Psalm will flag it with the DeprecatedClass issue, and if you can't fix them all at once, you can add them to the baseline, which will suppress the issue, but keep track of it, so you can still use Psalm in continuous integration and not break on existing issues. I believe PHPStan has similar functionality.
Related
I know, that to create a new path in Qt from a given absolute path, you use QDir::makepath() as dir.makepath(path), as it is suggested in this question. I do not have any trouble in using it and it works fine. My question is directed, as to why the developers would not provide a static function to call in a way like QDir::makepath("/Users/me/somepath/");. Needing to create a new QDir instance seems unnecessary to me.
I can only think of two possible reasons:
1. The developers were "lazy" or did not have time so they did not add one as it is not absolutely necessary.
2. The instance of QDir on which mkpath(path) is called, will be set to path as well, so it would be convenient for further usage - but I can not seem to find any hints that this is the actual behaviour within the docs.
I know I repeat myself, but again, I do not need help as of how to do it, but I am much interested as of why one has to do it that way.
Thanks for any reason I might have missed.
Let's have a look at the code of said method:
bool QDir::mkdir(const QString &dirName) const
{
const QDirPrivate* d = d_ptr.constData();
if (dirName.isEmpty()) {
qWarning("QDir::mkdir: Empty or null file name");
return false;
}
QString fn = filePath(dirName);
if (d->fileEngine.isNull())
return QFileSystemEngine::createDirectory(QFileSystemEntry(fn), false);
return d->fileEngine->mkdir(fn, false);
}
Source: http://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/io/qdir.cpp#n1381
As we can see, a static version would be simple to implement:
bool QDir::mkdir(const QString &dirName) const
{
if (dirName.isEmpty()) {
qWarning("QDir::mkdir: Empty or null file name");
return false;
}
return QFileSystemEngine::createDirectory(QFileSystemEntry(dirName), false);
}
(see also http://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/io/qdir.cpp#n681)
First, the non-static method comes with a few advantages. Obviously there is something to using the object's existing file engine. But also, I would imagine the use-case of creating several directories under a specific directory (that the QDir already points to).
So why not provide both?
Verdict (tl/dr): I think the reason is simple code hygiene. When you use the API, the difference between QDir::makepath(path); and QDir().makepath(path); is slim. The performance hit of creating the object is also negligible, as you would reuse the same object if you happen to perform the operation more often. But on the side of the code maintainers, it is arguably much more convenient (less work and less error prone) to not maintain two versions of the same method.
I would like to use #rebus in OneWayClientMode and at the same time configure the endpoint addresses in code and not via app.config.
Is this possible? I can find no trace of it in the fluent configuration.
Basically, you have two options: 1) route messages explicitly when you send them, and 2) implement your own routing logic using `IDetermineMessageOwnership´
The first option is pretty easy, and it is pretty explicit - you can simply go bus.Advanced.Routing.Send(destination, message) whenever you send a message. You should of course take care to not hardcode the destination too many times which could lead to problems later on :)
The second options is also easy, but it is slightly more implicit - you can implement the IDetermineMessageOwnership interface which is basically a way to map a message type to an endpoint, and then make Rebus use it like this:
Configure.With(...)
.(...)
.MessageOwnership(m => m.Use(myImplementation))
.(...)
Unless I was going to do only one or two bus.Sends, I would go for the latter option :) happy routing!
I'd like to give a more explicit example of option 2, because I had to search through the examples to find out how to type in "myImplementation", and it is really quite simple. Suppose you want a queue identified by sWorkerId to receive all messages, this is what you do:
Configure.With(...
.MessageOwnership(o => o.Use(new RebusConfig(sWorkerId)))
.CreateBus()
.Start(RebusConfig.NumberOfWorkers)
RebusConfig implements IDetermineMessageOwnership as:
public class RebusConfig : IDetermineMessageOwnership
{
private string m_sWorkerRoleEndpoint;
public RebusConfig(string sWorkerRoleEndpointId)
{
m_sWorkerRoleEndpoint = sWorkerRoleEndpointId;
}
public string GetEndpointFor(Type messageType)
{
return m_sWorkerRoleEndpoint;
}
}
Hope this helps ...
I'm putting together a very basic sort of "hello world" app with SignalR, with the minor caveat that it's self-hosted, which introduces an additional wrinkle or two. Basically, I'm trying to figure out the right way to call methods on my client(s) from the server.
On my client, for instance, I've got a method that looks like this:
roomHub.onEcho = function (msg) {
console.log("onEcho called: " + msg);
};
And I can call it successfully from my server-side hub like so:
public class RoomHub : Hub
{
public void Echo(string echo)
{
Clients.onEcho(echo);
}
}
And it works, but of course, it calls all the clients, not just one. And in the various samples I've seen online (e.g., https://github.com/SignalR/SignalR/blob/master/samples/Microsoft.AspNet.SignalR.Hosting.AspNet.Samples/Hubs/Benchmark/HubBench.cs, I see all sorts of commands that make it look like I should be able to specify who gets called, e.g.:
public void Echo(string echo)
{
Clients.Caller.onEcho(echo);
Clients.Caller(Context.ConnectionId).onEcho(echo);
Clients.All.onEcho(echo);
}
But I can't get any of the above syntaxes to work. For Clients.All.onEcho() and Clients.Caller.onEcho(), absolutely nothing happens. For Clients.Caller(Context.ConnectionId).onEcho(), Firebug tells me that it's actually trying to call a Caller() method on my JavaScript roomHub instance, which of course isn't there.
Here's the weird bit, though. If I look at the Hub class, I can see why none of these work - because the Hub constructor overrides a bunch of the properties of its "Clients" object with NullClientProxies:
protected Hub()
{
Clients = new HubConnectionContext();
Clients.All = new NullClientProxy();
Clients.Others = new NullClientProxy();
Clients.Caller = new NullClientProxy();
}
But I'm kinda mystified as to why it does that - or why the samples seem to work anyway - or what the expected approach should be.
Any thoughts? What am I doing wrong here?
We've been updating docs recently so you've probably seen lots of inconsistent data around the place. The latest version of SignalR is 1.0 alpha2 ( http://weblogs.asp.net/davidfowler/archive/2012/11/11/microsoft-asp-net-signalr.aspx ). All of the documentation has been updated to show the new syntax so if you're using an older version, please upgrade. Check out the wiki for examples https://github.com/SignalR/SignalR/wiki/Hubs
I've been following GUI extensions and notice examples use either _isEnabled or isEnabled, without the underscore. Both seem to work to extend or possibly replace existing functionality.
isEnabled
For example, the PowerTools base class (which doesn't seem to "extend" existing functionality) has:
PowerTools.BaseCommand.prototype.isEnabled = function(selection, pipeline)
{
var p = this.properties;
if (!p.initialized)
{
this.initialize();
}
if (!this.isToolConfigured())
{
return false;
}
if (this.isValidSelection)
{
return this.isValidSelection(selection, pipeline);
}
return true;
};
A tool can use this base class and declare .isValidSelection, for example:
PowerTools.Commands.CountItems.prototype.isValidSelection =
function (selection) { ... }
_isEnabled
I see Anguilla uses ._isEnabled for existing functionality (in Chrome's console in numerous places in the code). For example, WhereUsed has:
Tridion.Cme.Commands.WhereUsed.prototype._isAvailable =
function WhereUsed$_isAvailable(selection) ...
Private functions?
I'm familiar with a preceding underscore being a naming convention for private variables. Are the _isEnabled and other functions that start with an underscore "private?" If so, then
How should we extend (add additional functionality to existing code) these functions?
How should we replace (not have existing code run, but have ours run instead as in an "override") these?
I'm assuming the same approach applies to other functions that start with an underscore such as _isAvailable, and _invoke.
The following methods are called for a command:
isAvailable
isEnabled
invoke
The base class for all commands - Tridion.Core.Command - has a standard implementation of these methods. For the most part, this default implementation allows for extensions to Commands. They also call the underscore methods (_isAvailable, _isEnabled, and _execute).
I don't know why the CME commands only overwrite the underscore methods. Maybe someone thought it was just easier that way. They should be consider private (or the equivalent of "protected" in C#), so it actually seems like a bad practice to me.
It would be cleaner to implement the proper methods (isAvailable, isEnabled, and invoke) and then call the base implementation using this.callBase. However, you might need to stop the pipeline in this case, or also overwrite the underscore methods, in order to avoid your return value getting overwritten by the default underscore methods. It depends on the command you are implementing or extending.
In short: using the underscore methods is probably bad practice, but the Core implementation does seem to make it harder for you to do it "right". So I'd aim to avoid the underscore methods, but not sweat it if it turns out to be too hard to do so.
P.S. isValidSelection is a PowerTools-only method which separates the common logic that they all need from the logic specific to each command.
I'm in my module file. I want to define some complex variables for use throughout the module. For simple things, I'm doing this:
function mymodule_init() {
define('SOME_CONSTANT', 'foo bar');
}
But that won't work for more complex structures. Here are some ideas that I've thought of:
global:
function mymodule_init() {
$GLOBALS['mymodule_var'] = array('foo' => 'bar');
}
variable_set:
function mymodule_init() {
variable_set('mymodule_var', array('foo' => 'bar'));
}
property of a module class:
class MyModule {
static $var = array('foo' => 'bar');
}
Variable_set/_get seems like the most "drupal" way, but I'm drawn toward the class setup. Are there any drawbacks to that? Any other approaches out there?
I haven't seen any one storing static values that are array objects.
For simple values the drupal way is to put a define in the begining of a modules .module file. This file is loaded when the module is activated so that is enough. No point in putting it in the hook_init function.
variable_set stores the value in the database so don't run it over and over. Instead you could put it in your hook_install to define them once. variable_set is good to use if the value can be changed in an admin section but it's not the best choice to store a static variable since you will need a query to fetch it.
I think all of those methods would work. I have never used it in this fashion, but I believe the context module (http://drupal.org/project/context) also has its own API for storing variables in a static cache. You may want to check out the documentation for the module.
It's always a good practice to avoid globals. So that makes your choice a bit easier.
If you err towards a class, you'll be writing code that is not consistent with the D6 standards. There are a lot of modules that do it but I personally like to keep close to the Drupal core so I can understand it better. And code that's written in different styles through the same application can have an adverse effect on productivity and maintenance.
variable_set() and define() are quite different. Use the former when you can expect that information to change (a variable). Use the latter for constants. Your requirements should be clear as which one to use.
Don't worry too much about hitting the database for variable_set/get. If your software is written well, it should not effect performance hardly at all. Performance work arounds like that should only be implemented if your applications has serious performance issues and you've tried everything else.